Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python arguments, for in items

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!

like image 698
stackuser10210 Avatar asked Dec 02 '25 08:12

stackuser10210


2 Answers

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)
like image 143
Mark Ransom Avatar answered Dec 06 '25 13:12

Mark Ransom


I think you should use directly :

python myscrypt.py 101 102 103

and

items = sys.argv
like image 41
Cydonia7 Avatar answered Dec 06 '25 12:12

Cydonia7