Sys. argv []
List of strings containing command line parameters. Obtain the parameters by subscript.
For example:
#!/usr/bin/python# Filename: using_sys.py import sys print 'The command line arguments are:'for i in sys.argv: print i print '\n\nThe PYTHONPATH is', sys.path, '\n'print argv[1]
argv[ 0 ] Indicates the file path. Of course, agv [] can also store multiple values. |
Getopt
Used to extract command line options and parameters, that is, sys. argv. The command line option makes program parameters more flexible. The short and long options modes are supported.
import getopt#python scriptname.py -f 'hello' --directory-prefix=/home -t --form at 'a' 'b'shortargs = 'f:t'longargs = ['directory-prefix=', 'format', '--f_long=']opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
The format of the getopt function is getopt. getopt ([command line parameter list], "short options", [long Option List]).
The colon (:) after the short option name indicates that this option must have additional parameters.
The equal sign (=) after the long option name indicates that this option must have additional parameters.
Returns opts and args.
Opts is a parameter option and its value tuples ('-F', 'Hello'), ('-t', ''), ('-- format ', ''), ('-- directory-prefix','/home '))
Args is a command line input ('A', 'B') that removes useful parameters ')
Then, you can retrieve all the command line options and their corresponding parameters by traversing opts.
You can retrieve the options and parameters of all commands by traversing opts,
for opt, val in opts: if opt in ( '-f', '--f_long' ): pass if .... |
Analyze different promotional item parameters for different processing. Generally, the option parameter list is printed as a help option.
The typical use of getopt is also provided in python Documentation:
import getopt, sysdef main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None verbose = False for o, a in opts: if o == "-v": verbose = True elif o in ("-h", "--help"): usage() sys.exit() elif o in ("-o", "--output"): output = a else: assert False, "unhandled option" # ...if __name__ == "__main__": main()