Reputation: 352
I'd like to pass a list of integers as an argument to a python script.
Example code:
items = sys.argv[1]
for item in items:
print item
My command would be:
python myscript.py 101,102,103
The problem is that 'for in' is giving me each digit rather than each item as delimited by the commas.
I'm sure there's an easy answer. How do I loop through the delimted values rather than single digits?
Thanks very much!
Upvotes: 2
Views: 3827
Reputation:
The command line argument is passed to your script as a single string so you need to split it using the ',' as a delimiter to return individual integers.
items = sys.argv[1]
for item in items.split(','):
print item
Upvotes: 2
Reputation: 308266
Normally the command line arguments are separated by spaces. The comma separated numbers are coming in as a single string, and the for
is splitting the string into characters. You need to split it by commas: items.split(',')
. Once you do that you'll find that you still have strings, so you need to convert each string to an integer.
items = argv[1]
for item in items.split(','):
print int(item)
Upvotes: 6
Reputation: 236034
Split the input:
items = sys.argv[1].split(',')
for item in items:
print item
Upvotes: 2
Reputation: 3826
I think you should use directly :
python myscrypt.py 101 102 103
and
items = sys.argv
Upvotes: 3