Command-line arguments in Python show up in sys.argv
as a list of strings (so you'll need to import the sys
module).
For example, if you want to print all passed command-line arguments:
import sys
print(sys.argv) # Note the first argument is always the script filename.
Command-line options are sometimes passed by position (e.g. myprogram foo bar
) and sometimes by using a "-name value" pair (e.g. myprogram -a foo -b bar
).
Here's a simple way to parse command-line pair arguments. It scans the argv
list looking for -optionname optionvalue
word pairs and places them in a dictionary for easy retrieval. The code is heavily commented to help Python newcomers.