将元组作为命令行参数传递 [英] 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)'
接收.我尝试用type=tuple
代替argparse.add_argument
,但是在这里没有用.
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]
的列表.
如果必须有一个元组,可以执行以下操作:
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屋!