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!
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)
I think you should use directly :
python myscrypt.py 101 102 103
and
items = sys.argv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With