我有一个通过命令行参数运行的python程序。我已经使用了sys
模块。
下面是我的test.py
Python文件,其中包含所有参数:
if len(sys.argv) > 1:
files = sys.argv
get_input(files)
get_input
方法位于另一个我定义了options
的Python文件中。
options = {
'--case1': case1,
'--case2': case2,
}
def get_input(arguments):
for file in arguments[1:]:
if file in options:
options[file]()
else:
invalid_input(file)
要运行:
python test.py --case1 --case2
我的目的是要向用户显示所有命令,以防他们想要阅读文档。
他们应该能够读取所有软件包中通常读取帮助python test.py --help
的所有命令。有了它们,他们应该能够研究他们可以运行的所有命令。
我该怎么做?
答案 0 :(得分:2)
Python开发人员可以引以为傲的最高质量之一就是使用内置库而不是自定义库。因此,我们使用argparse
:
import argparse
# define your command line arguments
parser = argparse.ArgumentParser(description='My application description')
parser.add_argument('--case1', help='It does something', action='store_true')
parser.add_argument('--case2', help='It does something else, I guess', action='store_true')
# parse command line arguments
args = parser.parse_args()
# Accessing arguments values
print('case1 ', args.case1)
print('case2 ', args.case2)
您现在可以使用python myscript.py --case1
之类的cmd参数
这带有一个默认的--help
参数,您现在可以像这样使用:python myscript.py --help
,它将输出:
usage: myscript.py [-h] [--case1] [--case2]
My application description
optional arguments:
-h, --help show this help message and exit
--case1 It does something
--case2 It does something else, I guess
答案 1 :(得分:1)
您好,您可以使用选项解析器并添加选项和相关帮助信息。
默认情况下,它具有帮助选项,该选项显示您添加的所有可用选项。
详细文档为here。下面是示例。
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()