通过argparse将列表作为参数

发布于 2025-02-06 09:44:38 字数 323 浏览 1 评论 0原文

是否可以将列表变量作为参数传递给ArgParse模块?

已经看到它使用nargs选项

parser.add_argument('--my_arg', --nargs='+', type=int)

并将某些值传递给:

python script.py --my_arg 2 6 9

相反,是否可以执行以下操作?

my_list=[2,6,9]

python script.py --my_arg my_list

Is it possible to pass a list variable as an argument to the argparse module?

It has been seen to use nargs option

parser.add_argument('--my_arg', --nargs='+', type=int)

and pass some values as:

python script.py --my_arg 2 6 9

Instead, is it possible to do the following?

my_list=[2,6,9]

python script.py --my_arg my_list

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

南烟 2025-02-13 09:44:38

这取决于操作系统和所使用的外壳。例如,如果您在类似于Unix的系统上并且使用ZSH,则可以

my_list=(2 6 9)
python script.py --my_arg $my_list

在此处宽恕ZSH,因为如果您省略索引,它将扩展整个数组,并且与大多数壳不同,它不会拆分my_list 如果其中有空格,则为单独的单词。在bash中,i think 您必须做这样的事情,

my_list=(1 2 "hello there")
python script.py --my_arg "${my_list[@]}"

例如 bash手册

This depends on the operating system and shell used. For example, if you are on a unix-like system and using zsh, you could do

my_list=(2 6 9)
python script.py --my_arg $my_list

Zsh is quite forgiving here as it will expand entire arrays if you omit the index and, unlike most shells, it won't split elements of my_list into separate words if there are spaces in them. In Bash, I think you have to do something like this

my_list=(1 2 "hello there")
python script.py --my_arg "${my_list[@]}"

Chech the bash manual on arrays for details.

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