python命令行传参详解,optparse模块OptionParse类的学习
官网链接:https://docs.python.org/3/library/optparse.html
https://docs.python.org/2/library/argparse.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)
这样就可以指定文件做操作,传参中有啥参数也可以做对应参数了。
-h或者--help可以查看帮助信息,指定参数的介绍信息
添加-q参数,多了一组键值对,命令行加上-q值是假,不加也就是默认是真。(自解:可用于某个功能或其它是否开启或其他并给出默认状态)
from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() print(options,args)
官网介绍
optparse是一个比旧getopt模块更方便、灵活和强大的命令行选项解析库。 optparse使用更具声明性的命令行解析风格:创建 的实例 OptionParser,用选项填充它,然后解析命令行。optparse允许用户在传统的 GNU/POSIX 语法中指定选项,并额外为您生成使用和帮助消息。 这是optparse在简单脚本中使用的示例: from optparse import OptionParser ... parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() 使用这几行代码,您的脚本用户现在可以在命令行上执行“常规操作”,例如: <yourscript> --file=outfile -q 当它解析命令行时,根据用户提供的命令行值optparse设置options返回的对象的属性 parse_args()。当parse_args()解析此命令行返回时,options.filenamewill be"outfile"并且options.verbosewill be False。 optparse支持长选项和短选项,允许将短选项合并在一起,并允许选项以多种方式与其参数相关联。因此,以下命令行都等效于上面的示例: <yourscript> -f outfile --quiet <yourscript> --quiet --file outfile <yourscript> -q -foutfile <yourscript> -qfoutfile 此外,用户可以运行以下之一 <yourscript> -h <yourscript> --help 并且optparse将打印出你的脚本选项的简介: Usage: <yourscript> [options] Options: -h, --help show this help message and exit -f FILE, --file=FILE write report to FILE -q, --quiet don't print status messages to stdout 其中yourscript的值是在运行时确定的(通常来自 sys.argv[0])。