Question 7.14: You want to run a Python program from the command line and p......

You want to run a Python program from the command line and pass it parameters.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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).

Related Answered Questions

Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...