一:threading VS Thread

众所周知,python是支持多线程的,而且是native的线程,其中threading是对Thread模块做了包装,可以更加方面的被使用,threading模块里面主要对一些线程操作对象化了,创建了Thread的类。

使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行,一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的类里面,用例如下:

①使用Thread来实现多线程

#!/usr/bin/env python
#-*- coding:utf-8 -*- import string
import threading
import time def threadMain(a):
global count,mutex
#获得线程名
threadname = threading.currentThread().getName() for x in xrange(0,int(a)):
#获得锁
mutex.acquire()
count += 1
#释放锁
mutex.release()
print threadname,x,count
time.sleep() def main(num):
global count,mutex
threads = []
count = 1
#创建一个锁
mutex = threading.Lock()
#先创建线程对象
for x in xrange(0,num):
threads.append(threading.Thread(target = threadMain,args=(10,)))
for t in threads:
t.start()
for t in threads:
t.join() if __name__ == "__main__":
num = 4
main(num);

②使用threading来实现多线程

#!/usr/bin/env python
#-*- coding:utf-8 -*- import threading
import time class Test(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self):
self._run_num = num def run(self):
global count,mutex
threadName = threading.currentThread.getName()
for x in xrange(0,int(self._run_num)):
mutex.acquire()
count += 1
mutex.release()
print threadName,x,count
time.sleep(1) if __name__ == "__main__":
global count,mutex
threads = []
num = 4
count = 1
mutex.threading.Lock()
for x in xrange(o,num):
threads.append(Test(10))
#启动线程
for t in threads:
t.start()
#等待子线程结束
for t in threads:
t.join()

二 : optparser VS getopt

①使用getopt模块处理Unix模式的命令行选项

getopt模块用于抽出命令行选项和参数,也就是sys.argv,命令行选项使得程序的参数更加灵活,支持短选项模式和长选项模式

例:python scriptname.py –f “hello” –directory-prefix=”/home” –t  --format ‘a’‘b’

getopt函数的格式:getopt.getopt([命令行参数列表],‘短选项’,[长选项列表])

其中短选项名后面的带冒号(:)表示该选项必须有附加的参数

长选项名后面有等号(=)表示该选项必须有附加的参数

返回options以及args

options是一个参数选项及其value的元组((‘-f’,'hello’),(‘-t’,’’),(‘—format’,’’),(‘—directory-prefix’,’/home’))

args是除去有用参数外其他的命令行 输入(‘a’,‘b’)

#!/usr/bin/env python
# -*- coding:utf-8 -*- import sys
import getopt def Usage():
print "Usage: %s [-a|-0|-c] [--help|--output] args..."%sys.argv[0] if __name__ == "__main__":
try:
options,args = getopt.getopt(sys.argv[1:],"ao:c",['help',"putput="]):
print options
print "\n"
print args for option,arg in options:
if option in ("-h","--help"):
Usage()
sys.exit(1)
elif option in ('-t','--test'):
print "for test option"
else:
print option,arg
except getopt.GetoptError:
print "Getopt Error"
Usage()
sys.exit(1)

②optparser模块

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import optparser
def main():
usage = "Usage: %prog [option] arg1,arg2..."
parser = OptionParser(usage=usage)
parser.add_option("-v","--verbose",action="store_true",dest="verbose",default=True,help="make lots of noise [default]")
parser.add_option("-q","--quiet",action="store_false",dest="verbose",help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f","--filename",metavar="FILE",help="write output to FILE")
parser.add_option("-m","--mode",default="intermediate",help="interaction mode: novice, intermediate,or expert [default: %default]")
(options,args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
if options.verbose:
print "reading %s..." %options.filename if __name__ == "__main__":
main()

python相似模块用例(一)的更多相关文章

  1. Python标准模块--threading

    1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...

  2. python 深入模块和包

    模块可以包含可执行语句以及函数的定义. 这些语句通常用于初始化模块. 它们只在 第一次 导入时执行.只在第一次导入的时候执行,第一次.妈蛋的第一次...后面再次导入就不执行了. [1](如果文件以脚本 ...

  3. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  4. python 使用模块

    Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用. 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env python # -*- co ...

  5. Day05 - Python 常用模块

    1. 模块简介 模块就是一个保存了 Python 代码的文件.模块能定义函数,类和变量.模块里也能包含可执行的代码. 模块也是 Python 对象,具有随机的名字属性用来绑定或引用. 下例是个简单的模 ...

  6. python 各模块

    01 关于本书 02 代码约定 03 关于例子 04 如何联系我们 1 核心模块 11 介绍 111 内建函数和异常 112 操作系统接口模块 113 类型支持模块 114 正则表达式 115 语言支 ...

  7. Python学习笔记4-如何快速的学会一个Python的模块、方法、关键字

    想要快速的学会一个Python的模块和方法,两个函数必须要知道,那就是dir()和help() dir():能够快速的以集合的型式列出该模块下的所有内容(类.常量.方法)例: #--encoding: ...

  8. Day5 模块及Python常用模块

    模块概述 定义:模块,用一砣代码实现了某类功能的代码集合. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,提供了代码的重用性.在Python中,一个.py文件就称之为一个模块(Mod ...

  9. python——常用模块

    python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的 ...

随机推荐

  1. C#中List和数组之间的转换

    一.List转数组 (从List<string>转到string[])   C# 代码   复制 List<string> listS=new List<string&g ...

  2. VC ++ 后台消息模拟

    —HWND TO=; —//TO=::FindWindow(_T("Chrome_RenderWidgetHostHWND"),NULL); —TO=::FindWindow(_T ...

  3. 设计模式之UML类图

    在学设计模式的过程中经常碰到各式各样的UML类图.那些眼花缭乱的符号有什么含义呢? 类图含义 类图中的关系 从网上找来一张图作为实例 依赖关系:比如动物依赖氧气和水,这里如学生要依赖自行车.用虚线箭头 ...

  4. Ubuntu 12.04 下安装git

    ---恢复内容开始--- 1.安装build-essential. 列出Git相关包(git-core 和 git-doc)所以来的各个安装包并安装: sudo apt-get build-dep g ...

  5. HibernateDaoSupport的getSession()与HibernateTemplate的区别

    在 Spring+Hibernate的集成环境里,如果DAO直接使用HibernateDaoSupport的getSession()方法获取 session进行数据操作而没有显式地关闭该session ...

  6. 使用正则表达式限制TextBox输入

    /// <summary> /// 使用正则表达式限制输入 /// </summary> public class TextBoxRegex : TextBox { // 正则 ...

  7. RoHS认证简介

    RoHS认证是<电气.电子设备中限制使用某些有害物质指令>(The restriction of the use of certain hazardous substances in el ...

  8. WIN ERROR:C:\Windows\System32\<LANG_NAME>\mstsc.exe.MUI

    Issue: When you upgrade Win7, you may found your remote desktop will not work. You may get following ...

  9. css案例学习之父子块的margin

    两边还会有些距离,这是body默认的. 代码: <head> <title>父子块的margin</title> <style type="text ...

  10. 克鲁斯卡尔(Kruskal)算法

    # include <stdio.h> # define MAX_VERTEXES //最大顶点数 # define MAXEDGE //边集数组最大值 # define INFINITY ...