How to read/process command line arguments?
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments.
What are some of the ways Python programmers can do this?
Related
Please note that optparse was deprecated in version 2.7 of Python:
http://docs.python.org/2/library/optparse.html. argparse is the replacement: http://docs.python.org/2/library/argparse.html#module-argparse
There are the following modules in the standard library:
Here is an example that uses the latter from the docs:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
optparse supports (among other things):
import sys
print("n".join(sys.argv))
sys.argv
is a list that contains all the arguments passed to the script on the command line.
Basically,
import sys
print(sys.argv[1:])
Just going around evangelizing for argparse which is better for these reasons.. essentially:
(copied from the link)
argparse module can handle positional and optional arguments, while optparse can handle only optional arguments
argparse isn't dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality
argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.
argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (eg 1, 2, or 3) be known in advance
argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args
and doing the parser dispatch manually
And my personal favorite:
add_argument()
to be specified with simple callables, while optparse requires hacking class attributes like STORE_ACTIONS
or CHECK_METHODS
to get proper argument checking 上一篇: 如何使用yesod
下一篇: 如何读取/处理命令行参数?