python相似模块用例


Posted in Python onMarch 04, 2016

一: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()

以上就是threading VS Thread、optparser VS getopt 的相互比较,希望对大家学习模块有所帮助。

Python 相关文章推荐
python将文本转换成图片输出的方法
Apr 28 Python
分分钟入门python语言
Mar 20 Python
python中退出多层循环的方法
Nov 27 Python
对python中xlsx,csv以及json文件的相互转化方法详解
Dec 25 Python
Python将json文件写入ES数据库的方法
Apr 10 Python
Python实现12306火车票抢票系统
Jul 04 Python
Python中的 sort 和 sorted的用法与区别
Aug 10 Python
Python中bisect的使用方法
Dec 31 Python
Tensorflow 多线程与多进程数据加载实例
Feb 05 Python
python 6.7 编写printTable()函数表格打印(完整代码)
Mar 25 Python
一篇文章带你搞定Ubuntu中打开Pycharm总是卡顿崩溃
Nov 02 Python
class类在python中获取金融数据的实例方法
Dec 10 Python
Python程序中用csv模块来操作csv文件的基本使用教程
Mar 03 #Python
举例简单讲解Python中的数据存储模块shelve的用法
Mar 03 #Python
Python中的数据对象持久化存储模块pickle的使用示例
Mar 03 #Python
Python和Perl绘制中国北京跑步地图的方法
Mar 03 #Python
python套接字流重定向实例汇总
Mar 03 #Python
Python设计模式中单例模式的实现及在Tornado中的应用
Mar 02 #Python
Python使用设计模式中的责任链模式与迭代器模式的示例
Mar 02 #Python
You might like
PHP二维数组的去重问题解析
2011/07/17 PHP
php 文章调用类代码
2011/08/11 PHP
php获取淘宝分类id示例
2014/01/16 PHP
yii实现CheckBox复选框在同一行显示的方法
2014/12/03 PHP
php实现paypal 授权登录
2015/05/28 PHP
php 在字符串指定位置插入新字符的简单实现
2016/06/28 PHP
php解析xml 的四种简单方法(附实例)
2016/07/11 PHP
PHP高效获取远程图片尺寸和大小的实现方法
2017/10/20 PHP
thinkPHP5框架设置404、403等http状态页面的方法
2018/06/05 PHP
浅谈PHP封装CURL
2019/03/06 PHP
基于PHP+mysql实现新闻发布系统的开发
2020/08/06 PHP
JavaScript窗口功能指南之在窗口中书写内容
2006/07/21 Javascript
固定背景实现的背景滚动特效示例分享
2013/05/19 Javascript
JS控制弹出新页面窗口位置和大小的方法
2015/03/02 Javascript
javascript实现拖放效果
2015/12/16 Javascript
jQuery的ajax和遍历数组json实例代码
2016/08/01 Javascript
nodeJS实现简单网页爬虫功能的实例(分享)
2017/06/08 NodeJs
详解vue+webpack+express中间件接口使用
2018/07/17 Javascript
Vue源码解析之数据响应系统的使用
2019/04/24 Javascript
解决Vue中使用keepAlive不缓存问题
2020/08/04 Javascript
微信小程序获取当前时间及星期几的实例代码
2020/09/20 Javascript
通过数据库对Django进行删除字段和删除模型的操作
2015/07/21 Python
Django框架下在URLconf中指定视图缓存的方法
2015/07/23 Python
python中的格式化输出用法总结
2016/07/28 Python
Python两个内置函数 locals 和globals(学习笔记)
2016/08/28 Python
Python 搭建Web站点之Web服务器网关接口
2016/11/06 Python
Python爬取网易云音乐热门评论
2017/03/31 Python
python数字图像处理之高级滤波代码详解
2017/11/23 Python
详解python字节码
2018/02/07 Python
Python登录系统界面实现详解
2019/06/25 Python
Python文字截图识别OCR工具实例解析
2020/03/05 Python
Django model class Meta原理解析
2020/11/14 Python
详解CSS3原生支持div铺满浏览器的方法
2018/08/30 HTML / CSS
英国在线玫瑰专家:InterRose
2019/12/01 全球购物
工程造价管理专业大专生求职信
2013/10/06 职场文书
详解JAVA中的OPTIONAL
2021/06/14 Java/Android