Sending command line options to Python scripts
If you have some different options in your program and you want to turn them on or off, or feed your functions different arguments, then you can specify all of this from the command line.
You can read about the details of the optparser module here, but here are the basics:
Create an OptionParser object.
from optparse import OptionParser
parser = OptionParser()
Use parser.add_option() to add options that will be passed to the script from the command line. For example,
parser.add_option('--i', action='store', dest='input_file')
(options,args) = parser.parse_args
Each time you add an option, you have to specify:
- the option flag (say, -i or –infile for an input file). One dash for single characters, two dashes for anything longer.
- the action. This is typically store to store the variable, or store_true to use the option as an on-off switch.
- the destination. The option will be stored in an options object (described shortly . .)
There are other things you can add to, like defaults and help strings. See the documentation for more.
To get everything that was sent to the command line into your script, you get tell the OptionParser to get the parse the arguments from the command line like this:
(options,args) = parser.parse_args()
Now options has attributes named after the destination. In the example above, I added the command line option, -i, which will store the argument given right after it in the command line in options.input_file.
So if I called my script from the commandline like this:
python script.py -i mydata.txt
Then in my script, I could access the ‘mydata.txt’ that was provided on the commandline using
options.input_file
Or, to open the file specified on the command line within my script,
f = open(options.input_file)
Here’s a longer example:
import optparser
parser = OptionParser()
parser.add_option("-i",
action="store",
dest="infile",
help="specify the input file")
parser.add_option("-o",
action="store",
dest="outfile",
help="specify the output file")
# This is a boolean (True/False) option.
# I set the default to False; using the --tabs
# option at the command line will make it true.
parser.add_option("--tabs",
action="store_true",
dest="use_tabs",
default=False,
help="tell the script to export as tabs")
parser.add_option("--useless",
action="store",
dest="dummy_variable",
help="not used for anything")
(options, args) = parser.parse_args()
# This is how you access the options:
print options.infile
print options.outfile
print options.use_tabs
print options.dummy_variable
Now if you run this at the command prompt:
python test.py -i input.txt -o output.txt
then you’ll see that the options were passed to the script. If you don’t specify an option, its default value is None. You can also set a default value, like I’ve done for the –tabs option above.
Tags: command line, Python