Python is recommended for getting command line arguments
- 2020-07-21 09:04:15
- OfStack
This section looks at the sys, getopt module in python that handles command-line arguments
If you want to pass arguments to an python script, what is the corresponding argc in python, argv?
Module required: sys
Number of parameters: len(ES17en.argv)
Script name: ES21en. argv[0]
Parameter 1: ES24en. argv[1]
Parameter 2: ES27en. argv[2]
test.py
import sys
print " Script name: ", sys.argv[0]
for i in range(1, len(sys.argv)):
print " parameter ", i, sys.argv[i]
>>>python test.py hello world
Script name: ES36en.py
Parameter 1 hello
Parameter 2 world
Use the command line option in python:
For example, we need an ES48en.py script. It processes one file and outputs the result to another.
The script is required to meet the following conditions:
1. Use the -ES54en-ES55en option to distinguish between input and output files.
>>> python convert.py -i inputfile -o outputfile
2. Print out the help information with -h when you do not know which parameters are required for convert.py
>>> python convert.py -h
getopt function:
getopt.getopt(args, options[, long_options])
convert.py
python test.py -i inputfile -o outputfile
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
input_file=""
output_file=""
for op, value in opts:
if op == "-i":
input_file = value
elif op == "-o":
output_file = value
elif op == "-h":
usage()
sys.exit()
Code explanation:
a) sys. argv[1:] for the parameter list to be processed, sys. argv[0] is the script name, so use sys. argv[1:] to filter out the script name.
(b) "hi: ": Writes the option character in the analysis string when an option merely indicates the on-off state, i.e., when no additional parameter is followed. When the selected item is followed by an additional parameter, write the option character in the analysis string followed by a ":" sign.
So "hi:o:" means "h" is an on-off option;
"i:" and "o:" indicate that one parameter should follow.
c) calls the getopt function. The function returns two lists: opts and args.
opts is the analyzed format information. opts is a list of one tuple. Each element is :(option string, additional parameters). Empty string "" if there is no additional argument.
ops in the above example is: [(' h ', '), (' - i ', 'inputfile), (' - o', 'outputfile)]
args is the remaining command-line argument that is not part of the format information.
The third argument to the getopt function [, long_options] is an optional long option argument, with short options in the above example (e.g. -ES121en-ES122en)
Examples of long option formats:
--version
--file=error.txt
Make 1 script support both short and long options
getopt.getopt(sys.argv[1:], "hi:o:", ["version", "file="])
conclusion