将元组作为命令行参数传递 [英] Passing a tuple as command line argument

查看:62
本文介绍了将元组作为命令行参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是将元组作为命令行参数(如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆