Pure Programmer
Blue Matrix


Cluster Map

Command Line Arguments

L1

This page is under construction. Please come back later.

When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.

$ python Program.py Fred 123 Flintstone

In our programs we can access each of these arguments using the variables sys.argv[0], sys.argv[1], sys.argv[2], etc. The program name can be found in the variable with the 0 subscript. The user supplied arguments are in the variables with subscripts 1, 2, 3, etc.

CmdLineArgs1.py
#!/usr/bin/env python3;
import Utils
import sys

# Begin Main
print("Number of arguments: " + str((len(sys.argv) - 1)))
print("Program Name: " + sys.argv[0])
print("Arg 1: " + sys.argv[1])
print("Arg 2: " + sys.argv[2])
print("Arg 3: " + sys.argv[3])
print("Arg 4: " + sys.argv[4])

Output
$ python3 CmdLineArgs1.py Fred Barney Wilma Betty Number of arguments: 4 Program Name: CmdLineArgs1.py Arg 1: Fred Arg 2: Barney Arg 3: Wilma Arg 4: Betty $ python3 CmdLineArgs1.py Φρειδερίκος Барнеи ウィルマ 贝蒂 Number of arguments: 4 Program Name: CmdLineArgs1.py Arg 1: Φρειδερίκος Arg 2: Барнеи Arg 3: ウィルマ Arg 4: 贝蒂

Be sure to include the import sys line in your program in order to be able to access the sys.argv variables.

If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.

CmdLineArgs2.py
#!/usr/bin/env python3;
import Utils
import sys

# Begin Main
a = Utils.stoiWithDefault(sys.argv[1], 0)
b = Utils.stoiWithDefault(sys.argv[2], 0)
c = a + b
print("{0:d} + {1:d} = {2:d}".format(a, b, c))

Output
$ python3 CmdLineArgs2.py 326 805 326 + 805 = 1131

The example below converts the command line arguments to floating point values.

CmdLineArgs3.py
#!/usr/bin/env python3;
import Utils
import sys

# Begin Main
a = Utils.stodWithDefault(sys.argv[1], 0)
b = Utils.stodWithDefault(sys.argv[2], 0)
c = a + b
print("{0:f} + {1:f} = {2:f}".format(a, b, c))

Output
$ python3 CmdLineArgs3.py 3.21 7.01 3.210000 + 7.010000 = 10.220000

Questions

Projects

More ★'s indicate higher difficulty level.

References