Python 中的可选命令行参数
我正在尝试检索 Python 脚本(Windows 下的 2.7)的可选命令行参数,但事情进展并不顺利。代码是:
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', default = 'baz')
args = parser.parse_args(['-t'])
print args.t
如果我在没有参数的情况下运行“program.py
”,则args.t将打印为None。 如果我运行“program.py -t
”,args.t 将打印为 None。 如果我运行“program.py -t foo
”,args.t 将打印为 None。
为什么我无法将命令行中的值获取到 args.t 中?
I am trying to retrieve optional command line parameters for a Python script (2.7 under Windows) and things are not going smoothly. The code is:
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', default = 'baz')
args = parser.parse_args(['-t'])
print args.t
If I run "program.py
" with no parameter, args.t is printed as None.
If I run "program.py -t
", args.t is printed as None.
If I run "program.py -t foo
", args.t is printed as None.
Why am I not getting the value from the command line into args.t?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要将
['-t']
传递给 parse_args。只需这样做:使用您传递给 parse_args 的任何参数而不是命令行。因此,有了这个参数,无论你使用什么命令行,argparse 都看不到它。
Don't pass
['-t']
to parse_args. Just do:Any arguments you pass to parse_args are used instead of your command-line. So with that argument it doesn't matter what command-line you use, argparse never sees it.
该行将
命令行参数 ["-t"] 传递给解析器。您想要使用实际的命令行参数,因此将该行更改为
The line
is passing the command line arguments ["-t"] to the parser. You want to work with the actual command line arguments, so change the line to
使用 const 关键字参数:
运行它会产生:
Use the const keyword argument:
Running it yields: