Python Command Line Arguments
Python providesgetopta module to obtain command line arguments.
$ python test.py arg1 arg2 arg3
In Python, you can also usesysofsys.argvto obtain command line arguments:
sys.argv is the list of command line arguments.
len(sys.argv) is the number of command line arguments.
Note:sys.argv
Example
The test.py file code is as follows:
Example
# -*- coding: UTF-8 -*-
import sys
print 'Number of arguments:', len(sys.argv), ' arguments.'
print 'Argument list:', str(sys.argv)
Executing the above code, the output result is:
$ python test.py arg1 arg2 arg3 参数个数为: 4 个参数。 参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
getopt module
The getopt module is a module specifically for handling command line arguments, used to obtain command line options and arguments, i.e. sys.argv. Command line options make the program's arguments more flexible. Supports short option mode-and long option mode--。
This module provides two methods and one exception handler to parse command line arguments.
getopt.getopt method
The getopt.getopt method is used to parse the command line arguments list, the syntax format is as follows:
getopt.getopt(args, options[, long_options])
Method parameter description:
args: The list of command line arguments to be parsed.
options: Defined as a string format,optionsthe colon after:indicates that if this option is set, there must be an additional argument; otherwise, no argument is attached.
long_options: Defined in a list format,long_optionsthe equal sign after=indicates that the option must have an additional argument; without an equal sign, it means the option does not take an additional argument.
The return value of this method consists of two elements: the first is(option, value)a list of tuples. The second is the argument list, containing those without-or--the arguments.
The other method is getopt.gnu_getopt, which will not be introduced in detail here.
Exception getopt.GetoptError
This exception is triggered when the argument list is not found, or when the required argument of an option is empty.
The exception's argument is a string indicating the cause of the error. The attributemsgandoptis the error message for the related option.
Example
Suppose we create such a script, we can pass two file names to the script file through the command line, and at the same time we use another option to view the script usage. The script usage is as follows:
usage: test.py -i <inputfile> -o <outputfile>
The test.py file code is as follows:
Example
# -*- coding: UTF-8 -*-
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'The input file is:', inputfile
print 'The output file is:', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
Executing the above code, the output result is:
$ python test.py -h usage: test.py -i <inputfile> -o <outputfile> $ python test.py -i inputfile -o outputfile 输入的文件为: inputfile 输出的文件为: outputfileOther Extensions
Python Basic Syntax