There are a few ways to handle command-line arguments.
One is, as has been suggested, sys.argv
: an array of strings from the arguments at command line. Use this if you want to perform arbitrary operations on different kinds of arguments. You can cast the first two arguments into integers and print their sum with the code below:
import sys
n1 = sys.argv[1]
n2 = sys.argv[2]
print (int(n1) + int(n2))
Of course, this does not check whether the user has input strings or lists or integers and gives the risk of a TypeError
. However, for a range of command line arguments, this is probably your best bet - to manually take care of each case.
If your script/program has fixed arguments and you would like to have more flexibility (short options, long options, help texts) then it is worth checking out the optparse and argparse
(requires Python 2.7 or later) modules. Below are some snippets of code involving these two modules taken from actual questions on this site.
import argparse
parser = argparse.ArgumentParser(description='my_program')
parser.add_argument('-verbosity', help='Verbosity', required=True)
optparse
, usable with earlier versions of Python, has similar syntax:
from optparse import OptionParser
parser = OptionParser()
...
parser.add_option("-m", "--month", type="int",
help="Numeric value of the month",
dest="mon")
And there is even getopt
if you prefer C-like syntax...