官网链接:https://docs.python.org/3/library/optparse.html
from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") (options, args) = parser.parse_args() print(options,type(options),args,type(args)) #print(type([])) 结果:<class ‘list‘>
options,是个类,dest是键值对里的键,值是None,args是列表,空
没传参的时候
-f 空格指定字符串,会将它作为dest里filename的值,

我再加一个短横线,结果还是可以的 --f

使用--file 也可以

其它字符串,不在--file后的那个,无论在它前面还是后面,都加进了args列表里。

临时给程序加个-m

也是可以用的

后面再用这个的,被覆盖掉了

代码现在如下,调用它的值

调用它的值,点来调用

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
(options, args) = parser.parse_args()
with open(‘%s‘%options.filename,mode=‘w‘,encoding=‘utf-8‘) as f:
f.write(‘我是小马过河‘)
if "mcw" in args:
print(‘欢迎mcw‘,args)
这样就可以指定文件做操作,传参中有啥参数也可以做对应参数了。


有时间再补充后面的
原文:https://www.cnblogs.com/machangwei-8/p/15171141.html