You want to run a Python program from the command line and pass it parameters.
Import sys and use its argv property, as shown in the following example. This returns an array, the first element of which is the name of the program. The other elements are any parameters (separated by spaces) that were typed on the command line after the program name.
import sys for (i, value) in enumerate(sys.argv): print(“arg: %d %s ” % (i, value)) |
Running the program from the command line, with some parameters after it, results in the following output:
$ python cmd_line.py a b c arg: 0 cmd_line.py arg: 1 a arg: 2 b arg: 3 c |
Discussion
Being able to specify command-line arguments can be useful for automating the running of Python programs, either at startup (Recipe 3.20) or on a timed basis (Recipe 3.21).
See Also
For basic information on running Python from the command line, see Recipe 5.4.
In printing out argv, we used list enumerations (Recipe 6.8).