“大白兔奶糖”通过精心收集,向本站投稿了10篇Python中的getopt函数使用详解,这次小编给大家整理后的Python中的getopt函数使用详解,供大家阅读参考,也相信能帮助到您。
- 目录
篇1:Python中的getopt函数使用详解
作者:低调小一 字体:[增加 减小] 类型:
这篇文章主要介绍了Python中的getopt函数使用详解,是Python进阶学习中的重要知识,需要的朋友可以参考下
函数原型:
getopt.getopt(args, shortopts, longopts=[])
参数解释:
args:args为需要解析的参数列表,一般使用sys.argv[1:],这样可以过滤掉第一个参数(ps:第一个参数是脚本的名称,它不应该作为参数进行解析)
shortopts:简写参数列表
longopts:长参数列表
返回值:
opts:分析出的(option, value)列表对。
args:不属于格式信息的剩余命令行参数列表。
源码分析
在Android生成OTA的build系统中,common.py文件中的ParseOptions函数就是用来解析输入参数的,我们来通过该函数的实现来分析一下getopt的使用。
函数源码如下:
def ParseOptions(argv, docstring, extra_opts=“”, extra_long_opts=, extra_option_handler=None): try: opts, args = getopt.getopt( argv, “hvp:s:x” + extra_opts, [“help”, “verbose”, “path=”, “signapk_path=”, “extra_signapk_args=”, “java_path=”, “public_key_suffix=”, “private_key_suffix=”, “device_specific=”, “extra=”] + list(extra_long_opts)) except getopt.GetoptError, err: Usage(docstring) print “**”, str(err), “**” sys.exit(2) path_specified = False for o, a in opts: if o in (“-h”, “--help”): Usage(docstring) sys.exit() elif o in (“-v”, “--verbose”): OPTIONS.verbose = True elif o in (“-p”, “--path”): OPTIONS.search_path = a elif o in (“--signapk_path”,): OPTIONS.signapk_path = a elif o in (“--extra_singapk_args”,): OPTIONS.extra_signapk_args = shlex.split(a) elif o in (“--java_path”,): OPTIONS.java_path = a else: if extra_option_handler is None or not extra_option_handler(o, a): assert False, “unknown option ”%s“” % (o,) os.environ[“PATH”] = (os.path.join(OPTIONS.search_path, “bin”) + os.pathsep + os.environ[“PATH”]) return args
其中,extra_option_handler可以理解为函数指针,它的功能也是解析opts的键值对,
extra_option_handler源码如下:
def option_handler(o, a): if o in (“-b”, “--board_config”): pass # deprecated elif o in (“-k”, “--package_key”): OPTIONS.package_key = a elif o in (“-i”, “--incremental_from”): OPTIONS.incremental_source = a elif o in (“-w”, “--wipe_user_data”): OPTIONS.wipe_user_data = True elif o in (“-n”, “--no_prereq”): OPTIONS.omit_prereq = True elif o in (“-e”, “--extra_script”): OPTIONS.extra_script. = a elif o in (“-a”, “--aslr_mode”): if a in (“on”, “On”, “true”, “True”, “yes”, “Yes”): OPTIONS.aslr_mode = True else: OPTIONS.aslr_mode = False elif o in (“--worker_threads”): OPTIONS.worker_threads = int(a) else: return False return True
一般生成OAT全量包的参数argv如下:
代码如下:
argv = [‘-v‘, ‘-p‘, ‘out/host/linux-xxx‘, ‘-k‘, ‘build/target/product/security/testkey‘, ‘out/target/product/xxx/obj/PACKAGING/target_files_intermediates/xxx-target_files.zip‘, ‘out/target/product/xxx/xxx_0723.1340-ota.zip‘]
首先,对参数进行分析,其中短参数包括:
-v,-p,-k,
经过解析后,生成的结果如下所示:
代码如下:
pts = [(‘-v‘, ‘‘), (‘-p‘, ‘out/host/linux-x86‘), (‘-k‘, ‘build/target/product/security/testkey‘)]
args =[‘out/target/product/xxx/obj/PACKAGING/target_files_intermediates/xxx-target_files.zip‘, ‘out/target/product/xxx/xxx_20150723.1340-ota.zip‘]
篇2:Python Deque 模块使用详解
最近更 新
python之模拟鼠标键盘动作具体实现
python将多个文本文件合并为一个文本的代
python发送arp欺骗攻击代码分析
Python 字符串操作方法大全
天翼开放平台免费短信验证码接口使用实例
Python3.x和Python2.x的区别介绍
Python实现端口复用实例代码
python条件和循环的使用方法
tornado框架blog模块分析与使用
Python struct模块解析
热 点 排 行
Python入门教程 超详细1小时学会
python 中文乱码问题深入分析
比较详细Python正则表达式操作指
Python字符串的encode与decode研
Python open读写文件实现脚本
Python enumerate遍历数组示例应
Python 深入理解yield
Python+Django在windows下的开发
python 文件和路径操作函数小结
python 字符串split的用法分享
篇3:Python内置函数dir详解
这篇文章主要介绍了Python内置函数dir详解,本文讲解了命令介绍、使用实例、使用dir查找module下的所有类、如何找到当前模块下的类等内容,需要的朋友可以参考下
1.命令介绍
最近学习并使用了一个python的内置函数dir,首先help一下:
代码如下:
>>>help(dir)
Help on built-in function dir in module __builtin__:
dir
dir([object]) ->list of strings
Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
No argument: the names in the current scope.
Module object: the module attributes.
Type or class object: its attributes, and recursively the attributes of
its bases.
Otherwise: its attributes, its class‘s attributes, and recursively the
attributes of its class‘s base classes.
通过help,可以简单的认为dir列出指定对象或类的属性,
2.实例
下面是一个简单的测试:
代码如下:
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == ‘__main__‘:
print(“dir without arguments:”, dir())
print(“dir class A:”, dir(A))
print(“dir class A1:”, dir(A1))
a = A1()
print(“dir object a(A1):”, dir(a))
print(“dir function a.a:”, dir(a.a))
测试结果:
代码如下:
dir without arguments: [‘A‘, ‘A1‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘]
dir class A: [‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘a‘]
dir class A1: [‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘a‘, ‘a1‘]
dir object a(A1): [‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__module__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘a‘, ‘a1‘]
dir function a.a: [‘__call__‘, ‘__class__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__func__‘, ‘__ge__‘, ‘__get__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__self__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘]
3.使用dir查找module下的所有类
最初使用这个函数的初衷,就是在一个module中查找实现的类名,通过该函数可以很容易的实现,
比如把上面的测试程序保存为A.py,再建一个测试程序,内容如下:
代码如下:
import A
if __name__ == ‘__main__‘:
print(“dir module A:”, dir(A))
结果如下:
代码如下:
dir module A: [‘A‘, ‘A1‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘]
可以看出class A和A1都能够找到。
4.如何找到当前模块下的类
这是一个烦恼较长时间的一个问题,也没有搜到详细的解决方法,下面是我的集中实现方法。
4.1.方法一:在module下面直接调用
比如在上面的A.py最下面添加一行,即可在后续的代码中可以使用selfDir来查找当前的module下的类,修改后的代码如下:
代码如下:
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
curModuleDir=dir() # get dir of current file(module)
if __name__ == ‘__main__‘:
print(“dir without arguments:”, dir())
print(“dir class A:”, dir(A))
print(“dir class A1:”, dir(A1))
a = A1()
print(“dir object a(A1):”, dir(a))
print(“dir function a.a:”, dir(a.a))
print(“dir current file:”, curModuleDir)
4.2.方法二:import当前module
把当前module和别的import一样引用,代码如下:
代码如下:
# A.py
import A as this # import current module
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == ‘__main__‘:
print(“dir without arguments:”, dir())
print(“dir class A:”, dir(A))
print(“dir class A1:”, dir(A1))
a = A1()
print(“dir object a(A1):”, dir(a))
print(“dir function a.a:”, dir(a.a))
print(“dir current file:”, dir(this))
4.3.方法三:根据module名称查找module,然后调用dir
我们知道module下面有个属性__name__显示module名称,怎么能够根据module名称来查找module对象呢?可以借助sys.modules。代码如下:
代码如下:
import sys
class A:
def a(self):
pass
class A1(A):
def a1(self):
pass
if __name__ == ‘__main__‘:
print(“dir without arguments:”, dir())
print(“dir class A:”, dir(A))
print(“dir class A1:”, dir(A1))
a = A1()
print(“dir object a(A1):”, dir(a))
print(“dir function a.a:”, dir(a.a))
print(“dir current file:”, dir(sys.modules[__name__])) # 使用__name__获取当前module对象,然后使用对象获得dir
篇4:Python中的匿名函数使用简介
作者:廖雪峰 字体:[增加 减小] 类型:
这篇文章主要介绍了Python中的匿名函数的使用,lambda是各个现代编程语言中的重要功能,需要的朋友可以参考下
当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便,
在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
>>>map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])[1, 4, 9, 16, 25, 36, 49, 64, 81]
通过对比可以看出,匿名函数lambda x: x * x实际上就是:
def f(x): return x * x
关键字lambda表示匿名函数,冒号前面的x表示函数参数,
匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
>>>f = lambda x: x * x>>>f 同样,也可以把匿名函数作为返回值返回,比如: def build(x, y): return lambda: x * x + y * y 小结 Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。 这篇文章主要介绍了详解Python中find方法的使用,是Python学习中的基础知识,需要的朋友可以参考下 find()方法判断字符串str,如果起始索引beg和结束end索引能找到在字符串或字符串的一个子串中, 语法 以下是find()方法的语法: str.find(str, beg=0 end=len(string)) 参数 str -- 此选项指定要搜索的字符串。 beg -- 这是开始索引,默认情况下为 0, end -- 这是结束索引,默认情况下它等于字符串的长度。 返回值 如果找到此方法返回的索引,否则返回-1。 例子 下面的例子显示了find()方法的使用。 #!/usr/bin/pythonstr1 = “this is string example....wow!!!”;str2 = “exam”;print str1.find(str2);print str1.find(str2, 10);print str1.find(str2, 40); 当我们运行上面的程序,它会产生以下结果: 这篇文章主要介绍了详解Python中expandtabs()方法的使用,是Python入门中的基础知识,需要的朋友可以参考下 expandtabs()方法返回制表符,即该字符串的一个副本, ‘t‘已经使用的空间,可选择使用给定的tabsize(默认8)扩展。 语法 以下是expandtabs()方法的语法: str.expandtabs(tabsize=8) 参数 tabsize -- 此选项指定要替换为制表符“t‘ 的字符数. 返回值 此方法返回在制表符,即通过空格进行了扩展字符串,‘t‘的副本, 例子 下面的例子显示expandtabs()方法的使用。 #!/usr/bin/pythonstr = “this iststring example....wow!!!”;print “Original string: ” + str;print “Defualt exapanded tab: ” + str.expandtabs();print “Double exapanded tab: ” + str.expandtabs(16); 当我们运行上面的程序,它会产生以下结果: Original string: this is string example....wow!!!Defualt exapanded tab: this is string example....wow!!!Double exapanded tab: this is string example....wow!!! 这篇文章主要介绍了Python中tell方法的使用详解,是Python入门学习中的基础知识,需要的朋友可以参考下 tell()方法返回的文件内的文件读/写指针的当前位置, 语法 以下是tell()方法的语法: fileObject.tell() 参数 NA 返回值 此方法返回该文件中读出的文件/写指针的当前位置。 例子 下面的例子显示了tell()方法的使用, #!/usr/bin/python# Open a filefo = open(“foo.txt”, “rw+”)print “Name of the file: ”, fo.name# Assuming file has following 5 lines# This is 1st line# This is 2nd line# This is 3rd line# This is 4th line# This is 5th lineline = fo.readline()print “Read Line: %s” % (line)# Get the current position of the file.pos = fo.tell()print “Current Position: %d” % (pos)# Close opend filefo.close() 当我们运行上面的程序,它会产生以下结果: Name of the file: foo.txtRead Line: This is 1st lineCurrent Position: 18 这篇文章主要介绍了详解Python中的type()方法的使用,是Python入门中的基础知识,需要的朋友可以参考下 type()方法返回传递变量的类型,如果传递变量是字典那么它将返回一个字典类型。 语法 以下是type()方法的语法: type(dict) 参数 dict -- 这是字典 返回值 此方法返回传递变量的类型, 例子 下面的例子显示type()方法的使用 #!/usr/bin/pythondict = {‘Name‘: ‘Zara‘, ‘Age‘: 7};print “Variable Type : %s” % type (dict) 当我们运行上面的程序,它会产生以下结果: Variable Type : 这篇文章主要介绍了Python中的localtime方法使用详解,是Python入门学习的基础知识,需要的朋友可以参考下 localtime()方法类似gmtime()方法,但它转换秒数为本地时间,如果不设置秒时或None,所返回的当前时间使用time()方法。在dst标志被设置为1时,夏令时适用于给定的时间。 语法 以下是localtime()方法的语法: time.localtime([ sec ]) 参数 sec -- 这是秒数转换成结构struct_time来表示, 返回值 此方法不返回任何值。 例子 下面的例子显示了localtime()方法的使用。 #!/usr/bin/pythonimport timeprint “time.localtime() : %s” % time.localtime() 当我们运行上面的程序,它会产生以下结果: time.localtime() : (, 2, 17, 17, 3, 38, 1, 48, 0) 这篇文章主要介绍了详解Python中的strftime()方法的使用,是Python入门学习中的基础知识,需要的朋友可以参考下 strftime()方法转换成一个元组或struct_time表示时间所指定的格式参数所返回gmtime()或localtime()为一个字符串, 当t不设置,所返回当前时间使用localtime()方法。格式必须是字符串。异常ValueError被挂起,如果t在任何字段的允许范围之外。 语法 以下是strftime()方法的语法: time.strftime(format[, t]) 参数 t -- 这是以秒为单位来进行格式化的时间。 format -- 这是将用于格式化给定的时间的指令。下面的指令可以嵌入格式字符串: 指令 %a - 简写的星期几 %A - 完整的星期几 %b - 缩写的月份名称 %B - 完整的月份名称 %c - 首选日期和时间表示 %C - 世纪值(年份除以100,范围从00到99) %d - 该月的第几天(01?31) %D - 类似 %m/%d/%y %e - 该月的一天(1?31) %g - 类似于%G,但是没有世纪 %G - 对应于ISO周数4位数的年份(参见%V) %h - 类似于 %b %H - 小时,使用24小时制(00?23) %I - 小时,使用12小时制(01?12) %j - 一年中的哪一天(001?366) %m - 月份(01?12) %M - 分钟 %n - 换行符 %p - 根据给定的时间值am或pm %r - 时间在上午和下午的符号:am/pm %R - time in 24 hour notation %S - 秒 %t - 制表符 %T - 当前时间,等于 %H:%M:%S %u - 工作日为数字(1到7),星期一= 1, 警告:在Sun Solaris上周日=1 %U - 当年的周数,第一个星期日作为第一周的第一天 %V - 本年度ISO 8601的周数(01到53),其中,第1周是在本年度至少4天的第一个星期,星期一作为一周的第一天 %W - 当年的周数,与第一个星期一作为第一周的第一天 %w - 星期为一个小数,星期日=0 %x - 没有时间的日期表示 %X - 无日期首选的时间表示 %y - 一年无世纪(范围从00到99) %Y - 今年,包括世纪 %Z or %z - 时区或名称或缩写 %% -文字%字符 返回值 此方法不返回任何值。 例子 下面的例子显示strftime()方法的使用。 #!/usr/bin/pythonimport timet = (2009, 2, 17, 17, 3, 38, 1, 48, 0)t = time.mktime(t)print time.strftime(“%b %d %Y %H:%M:%S”, time.gmtime(t)) 当我们运行上面的程序,它会产生以下结果: Feb 18 2009 00:03:38
★ [作文素材]python if not Secretspeakingif篇5:详解Python中find方法的使用
篇6:详解Python中expandtabs方法的使用
篇7:Python中tell方法的使用详解
篇8:详解Python中的type方法的使用
篇9:Python中的localtime方法使用详解
篇10:详解Python中的strftime方法的使用
Python中的getopt函数使用详解(精选10篇)