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
282 views
in Technique[技术] by (71.8m points)

specifying a list as a command line argument in python

I am using getopt to process a command line optional argument, which should accept a list. Something like this:

foo.py --my_list=[1, 2, 3, 4,5] 

But this trims everything after "[1,"

My questions are: A) Is there a way to specify a list without converting it into a string? (using getopt)

B) If I am to convert the list into a string, how to convert this list to a string? e.g. something like mylist.split("?") to get rid of square brackets ?? is there a better way?

Thank you

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are two options that I can think of:

  • Use optparse, and use append action to specify what you want to do as: foo.py --my_list=1 --my_list=2 ....
  • Specify your commandline as foo.py --my_list='1,2,3,4,5', and then use x.split(',') to get your values in a list. You can use getopt or optparse for this method.

The advantage of the first method is that you can get integer values in the list directly, at the expense of the commandline being longer (but you can add a single-charecter option for --my_list if you want). The advantage of the second is shorter command line, but after the split(), you need to convert the string values '1', '2', etc., to integers (pretty easy as well).


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

...