How to iterate over command line arguments? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to iterate over command line arguments? (/thread-14209.html) |
How to iterate over command line arguments? - zBernie - Nov-20-2018 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) RE: How to iterate over command line arguments? - ichabod801 - Nov-20-2018 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. RE: How to iterate over command line arguments? - zBernie - Nov-20-2018 (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?
RE: How to iterate over command line arguments? - wavic - Nov-20-2018 >>> type(sys.argv) <class 'list'>Iterating over a string returns each letter. for element in sys.argv: should do it.
RE: How to iterate over command line arguments? - zBernie - Nov-23-2018 (Nov-20-2018, 07:01 AM)wavic Wrote:>>> type(sys.argv) <class 'list'>Iterating over a string returns each letter. Thanks, I wound up using this which eliminates the script name in [0]: for jpgfile in sys.argv[1:]: RE: How to iterate over command line arguments? - wavic - Nov-23-2018 Exactly! Look at the argparse module. It allows much more flexibility and control over the arguments. |