将元组作为命令行参数传递 [英] Passing a tuple as command line argument
问题描述
我的要求是将元组作为命令行参数传递,如
My requirement is to pass a tuple as command line argument like
--data (1,2,3,4)
我尝试使用 argparse
模块,但是如果我像这样传递它,它会以字符串 '(1,2,3,4)'
的形式接收.我尝试为 argparse.add_argument
提供 type=tuple
,但在这里没有用.
I tried to use the argparse
module, but if I pass like this it is receiving as the string '(1,2,3,4)'
. I tried by giving type=tuple
for argparse.add_argument
, but is of no use here.
我是否必须添加一个新的类型类并将其传递给 add_argument
的类型参数?
Do I have to add a new type class and pass that to type argument of add_argument
?
更新
我根据答案尝试了 ast.literal_eval
.感谢那.但它在结果中给出了空格,如下所示.
I tried the ast.literal_eval
based on answers. Thanks for that. But it is giving spaces in the result as shown below.
(1,2,3,4)
<type 'str'>
(1, 2, 3, 4)
<type 'tuple'>
推荐答案
将 data
参数的 nargs
设置为 nargs="+"
(意味着一个或多个)并输入int
,然后您可以在命令行上像这样设置参数:
Set nargs
of the data
argument to nargs="+"
(meaning one or more) and type to int
, you can then set the arguments like this on the command line:
--data 1 2 3 4
args.data
现在将是 [1, 2, 3, 4]
的列表.
args.data
will now be a list of [1, 2, 3, 4]
.
如果你必须有一个元组,你可以这样做:
If you must have a tuple, you can do:
my_tuple = tuple(args.data)
综合起来:
parser = argparse.ArgumentParser()
parser.add_argument('--data', nargs='+', type=int)
args = parser.parse_args()
my_tuple = tuple(args.data)
这篇关于将元组作为命令行参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!