Command-line Arguments

The sys module also provides access to any command-line arguments via the sys.argv. Command-line arguments are those arguments given to the program in addition to the script name on invocation. Historically, of course, these arguments are so named because they are given on the command-line along with the program name in a text-based environment like a Unix- or DOS-shell. However, in an IDE or GUI environment, this would not be the case. Most IDEs provide a separate window with which to enter your “command-line arguments.” These, in turn, will be passed into the program as if you started your application from the command-line. Those of you familiar with C programming may ask, “Where is argc?” The strings “argv” and “argv” stand for “argument count” and “argument vector,” respectively. The argv variable contains an array of strings consisting of each argument from the command-line while the argc variable contains the number of arguments entered. In Python, the value for argc is simply the number of items in the sys.argv list, and the first element of the list, sys.argv[0], is always the program name. Summary:
sys.argv is the list of command-line arguments
len(sys.argv) is the number of command-line arguments (a.k.a. argc)
Let us create a small test program called with the following lines:


import sys
print 'you entered', len(sys.argv), 'arguments…'
print 'they were:', str(sys.argv)

Here is an example invocation and output of this script:

% 76 tales 85 hawk
you entered 5 arguments…
they were: ['', '76', 'tales', '85', 'hawk']

You may also like...