Several ways of python command line parameter parsing

python command line parsing

Optional: getopt, optparse

getopt:

import sys
import getopt
import optparse

opts, args = getopt.getopt(sys.argv[1:], "hi:o:p", ["haha", "xixi", "qiuqiu"])

print opts

Order:

python get_opt.py -hi "123"

output:

[('-h', ''), ('-i', '123')]

explain:

getopt.getopt (1, 2, 3)

The first parameter is the input parameter of the system, usually sys.argv[1:]

The second parameter is the short representation of the parameter. For example, h means help. If you need the value of the parameter, you can add a colon, and if there is no value, an error message will be reported.

The third parameter is a representation of a long list of parameter names, usually in the same order as the second, but it is not required.

When you need to use parameters, you only need to traverse the return value, opts will do

All usage:

import sys
import getopt
import optparse

opts, args = getopt.getopt(sys.argv[1:], "hi:h", ["help", "input", "haha"])

config = {}

for opt_name, value in opts:
    print opt_name, value
    if opt_name in ["--input", "i"]:
        config["input_value"] = value

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854930&siteId=291194637