Python 中的可选命令行参数

发布于 2025-01-05 23:02:25 字数 475 浏览 4 评论 0原文

我正在尝试检索 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谜兔 2025-01-12 23:02:25

不要将 ['-t'] 传递给 parse_args。只需这样做:

args = parser.parse_args()

使用您传递给 parse_args 的任何参数而不是命令行。因此,有了这个参数,无论你使用什么命令行,argparse 都看不到它。

Don't pass ['-t'] to parse_args. Just do:

args = parser.parse_args()

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.

瘫痪情歌 2025-01-12 23:02:25

该行将

args = parser.parse_args(["-t"])

命令行参数 ["-t"] 传递给解析器。您想要使用实际的命令行参数,因此将该行更改为

args = parser.parse_args()

The line

args = parser.parse_args(["-t"])

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

args = parser.parse_args()
自在安然 2025-01-12 23:02:25

使用 const 关键字参数

import argparse
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', const = 'baz', default = 'baz')
args = parser.parse_args()
print args.t

运行它会产生:

% test.py          # handled by `default`
baz
% test.py -t       # handled by `const`
baz
% test.py -t blah
blah

Use the const keyword argument:

import argparse
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', const = 'baz', default = 'baz')
args = parser.parse_args()
print args.t

Running it yields:

% test.py          # handled by `default`
baz
% test.py -t       # handled by `const`
baz
% test.py -t blah
blah
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文