我希望能够为我的程序指定一个选项,既是标志又是变量。例如:
我有一个名为“--logging”的参数。如果未指定此参数,则希望将其设置为false(即action='store_true'),但如果指定了该参数,则希望执行两个操作。1)我想设置默认路径为“./log_file.log”,2)我想允许用户指定不同的日志文件位置。
好的,我想出了自己的解决方案。它依赖于nargs。这是代码:
#!/usr/bin/python
# example.py
import argparse
parser = argparse.ArgumentParser(description="Example of a single flag acting as a boolean and an option.")
parser.add_argument('--foo', nargs='?', const="bar", default=False)
args = parser.parse_args()
if args.foo:
print args.foo
else:
print "Using the default, boolean False."
> ./example.py
Using the default, boolean False.
> ./example.py --foo
bar
> ./example.py --foo baz
baz
没问题。你可以使用在PyMOTW about argparse中详细解释的这个表单。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--logging', action='store_true', default=False,
dest='logging_on',
help='Activate the logging')
results = parser.parse_args()
您可以使用logging_on来测试和输出代码中的值(将其替换为适合您的内容)。您还可以使用配置文件和/或文件日志路径的参数。