Python Forum

Full Version: How to iterate over command line arguments?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do you iterate over arguments passed to a script? I'm trying to use sys.argv as shown below, which does not work.

-Thanks


print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

for jpgfile in str(sys.argv):
    print(jpgfile)
How does it not work? It works for me, although note that looping over a string loops over each character in the string. You did import sys, right? It's not in your code.
(Nov-20-2018, 03:20 AM)ichabod801 Wrote: [ -> ]How does it not work? It works for me, although note that looping over a string loops over each character in the string. You did import sys, right? It's not in your code.

Here is what I got for output. How do I print each individual argument?

Output:
im-datestamp.py aaa bbb Number of arguments: 3 arguments. Argument List: ['./im-datestamp.py', 'aaa', 'bbb'] [ ' . / i m - d a t e s t a m p . p y ' , ' a a a ' , ' b b b ' ]
>>> type(sys.argv)
<class 'list'>
Iterating over a string returns each letter. for element in sys.argv: should do it.
(Nov-20-2018, 07:01 AM)wavic Wrote: [ -> ]
>>> type(sys.argv)
<class 'list'>
Iterating over a string returns each letter. for element in sys.argv: should do it.

Thanks, I wound up using this which eliminates the script name in [0]:

for jpgfile in sys.argv[1:]:
Exactly!

Look at the argparse module. It allows much more flexibility and control over the arguments.