How to Use python command line
Use the command line option in python:
For example, we need a convert. py script. It is used to process a file and output the processed result to another file.
The script must meet the following conditions:
1. Use the-I-o option to identify whether the parameter is an input file or an output file.
>>> Python convert. py-I inputfile-o outputfile
2. If you do not know which parameters are required for convert. py, use-h to print the help information.
>>> Python convert. py-h
Original form of the getopt function:
Getopt. getopt (args, options [, long_options])
Convert. py
02 import sys, getopt
03 opts, args = getopt. getopt (sys. argv [1:], "hi: o :")
04input_file = ""
05output_file = ""
06
07for op, value in opts:
08 if op = "-I ":
09 input_file = value
10 elif op = "-o ":
11 output_file = value
12 elif op = "-h ":
13 usage ()
14 sys. exit ()
Code explanation:
A) sys. argv [1:] is the list of parameters to be processed, and sys. argv [0] is the script name. Therefore, use sys. argv [1:] to filter out the Script Name.
B) "hi: o:": When an option only indicates the switch status, that is, when no additional parameter is added, the option character is written into the analysis string. When the option is followed by an additional parameter, write the option character in the analysis string and add. Therefore, "hi: o:" indicates that "h" is a switch option; "I:" and "o:" indicates that a parameter should be followed.
C) Call the getopt function. The function returns two lists: opts and args. Opts is the analyzed format information. Args is the remaining command line parameter that does not belong to the format information. Opts is a list of two-element groups. Each element is: (option string, additional parameter ). If no parameter is attached, it is an empty string ''.
The third parameter [, long_options] of the getopt function is an optional long option parameter. All of the preceding parameters are short options (such as-I-o)
Example of long option format:
-- Version
--Filepolicerror.txt
Allow a script to support both short and long options.
Getopt. getopt (sys. argv [1:], "hi: o:", ["version", "file ="])