Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

python - Passing a tuple as command line argument

My requirement is to pass a tuple as command line argument like

--data (1,2,3,4)

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.

Do I have to add a new type class and pass that to type argument of add_argument?

Update

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'>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 will now be a list of [1, 2, 3, 4].

If you must have a tuple, you can do:

my_tuple = tuple(args.data)

Putting it all together:

parser = argparse.ArgumentParser()
parser.add_argument('--data', nargs='+', type=int)
args = parser.parse_args()
my_tuple = tuple(args.data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...