Home > Articles

  • Print
  • + Share This
This chapter is from the book

4.11 Accessing Command-Line Arguments

Running a program from the command lets you provide the program an extra degree of flexibility. You can let the user specify command-line arguments; these are optional arguments that give information directly to the program on start-up. Alternatively, you can let the program prompt the user for the information needed. But use of command-line arguments is typically more efficient.

Command-line arguments are always stored in the form of strings. So—just as with data returned by the input function—you may need to convert this string data to numeric format.

To access command-line arguments from within a Python program, first import the sys package.

import sys

You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv.

key.jpg
argv       # If 'import sys.argv' used
sys.argv   # If sys imported as 'import sys'

In either case, argv refers to a list of command-line arguments, all stored as strings. The first element in the list is always the name of the program itself. That element is indexed as argv[0], because Python uses zero-based indexing.

For example, suppose that you are running quad (a quadratic-equation evaluator) and input the following command line:

python quad.py -1 -1 1

In this case, argv will be realized as a list of four strings.

Figure 4.5 illustrates how these strings are stored, emphasizing that the first element, argv[0], refers to a string containing the program name.

FIGURE 4.5

Figure 4.5. Command-line arguments and argv

In most cases, you’ll probably ignore the program name and focus on the other arguments. For example, here is a program named silly.py that does nothing but print all the arguments given to it, including the program name.

import sys
for thing in sys.argv:
    print(thing, end='  ')

Now suppose we enter this command line:

python  silly.py  arg1  arg2  arg3

The Terminal program (in Mac) or the DOS Box prints the following:

silly.py  arg1  arg2  arg3

The following example gives a more sophisticated way to use these strings, by converting them to floating-point format and passing the numbers to the quad function.

import sys

def quad(a, b, c):
    '''Quadratic Formula function.'''

    determin = (b * b - 4 * a * c) ** .5
    x1 = (-b + determin) / (2 * a)
    x2 = (-b - determin) / (2 * a)
    return x1, x2

def main():
    '''Get argument values, convert, call quad.'''

    s1, s2, s3 = sys.argv[1], sys.argv[2], sys.argv[3]
    a, b, c = float(s1), float(s2), float(s3)
    x1, x2 = quad(a, b, c)
    print('x values: {}, {}.'.format(x1, x2))

main()

The interesting line here is this one:

    s1, s2, s3 = sys.argv[1], sys.argv[2], sys.argv[3]

Again, the sys.argv list is zero-based, like any other Python list, but the program name, referred to as sys.arg[0], typically isn’t used in the program code. Presumably you already know what the name of your program is, so you don’t need to look it up.

Of course, from within the program you can’t always be sure that argument values were specified on the command line. If they were not specified, you may want to provide an alternative, such as prompting the user for these same values.

Remember that the length of the argument list is always N+1, where N is the number of command-line arguments—beyond the program name, of course.

Therefore, we could revise the previous example as follows:

import sys

def quad(a, b, c):
    '''Quadratic Formula function.'''

    determin = (b * b - 4 * a * c) ** .5
    x1 = (-b + determin) / (2 * a)
    x2 = (-b - determin) / (2 * a)
    return x1, x2

def main():
    '''Get argument values, convert, call quad.'''
    if len(sys.argv) > 3:
        s1, s2, s3 = sys.argv[1], sys.argv[2], sys.argv[3]
    else:
        s1 = input('Enter a: ')
        s2 = input('Enter b: ')
        s3 = input('Enter c: ')
    a, b, c = float(s1), float(s2), float(s3)
    x1, x2 = quad(a, b, c)
    print('x values: {}, {}.'.format(x1, x2))

main()

The key lines in this version are in the following if statement:

    if len(sys.argv) > 3:
        s1, s2, s3 = sys.argv[1], sys.argv[2], sys.argv[3]
    else:
        s1 = input('Enter a: ')
        s2 = input('Enter b: ')
        s3 = input('Enter c: ')
    a, b, c = float(s1), float(s2), float(s3)

If there are at least four elements in sys.argv (and therefore three command-line arguments beyond the program name itself), the program uses those strings. Otherwise, the program prompts for the values.

So, from the command line, you’ll be able to run the following:

python quad.py 1 -9 20

The program then prints these results:

x values: 4.0 5.0
  • + Share This
  • 🔖 Save To Your Account