命令行参数解析

sys.argv

接收执行python文件的参数,python xxx.py [ -a 1 -b 2 3 4 ]

argv.py

import sys

print(sys.argv)
print(sys.argv[0])

参数都保存在sys.argv中,其中第一个为脚本的文件名

# python argv.py ab c 1  3 
--------------------------------------------------------------
['argv.py', 'ab', 'c', '1', '3']
argv.py

getopt

在运行程序时,需要根据不同条件输入不同的命令行选项,目前有短选项和长选项两种方式。短选项为 "-" 加上单个字母,长选项为 "--" 加上一个单词

选项的写法要求:

短选项:

-"号后面要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开。长度任意,可以用引号。如以下是正确的:

-o
-oa
-obbbb
-o bbbb
-o "a b"

长选项:

"--"号后面要跟一个单词。如果还有些选项的附加参数,后面要紧跟"=",再加上参数。"="号前后不能有空格。如以下是正确的:

--help=file1

使用getopt()函数分析:

opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])#"ho:"也可以写成'-h-o:'

 第一个参数为输入参数去掉文件名

第二个参数表示短选项参数,当选项不需要值时就写单个字母,如果必须要有参数值的话在字母后面要跟 ":" , "ho:"表示 "h"是一个开关选项,传 -h 即可,或不传,  o 后面必须跟一个值,例如 -o 1 ,要么不传。"ho:"也可以写成"-h-o:","o:h", "-o:-h"

第三个参数表示长选项参数,跟短选项类似后面跟 "=" 表示参数要有值。["help", "output="]表示 help 是一个开关参数,--help 这么传就可以。output必须要带值,--output /abc,要么不传

返回值:

opts为分析出的格式信息。opts是一个两元组的列表。每个元素为:(选项串,附加参数值)。如果没有附加参数值则为空串''。

args为不属于格式信息的剩余的命令行参数

tgetopt.py

from scapy.all import *
import sys

class ArgParser():
    def arg_parser(self):
        try:
            opts, args = getopt.getopt(sys.argv[1:], "-h-f:-v", ['help','filename=','version'])
        except getopt.GetoptError as e:
            print("exception{}".format(e))
            self.usage()
            sys.exit()
        print("args :{}".format(args))
        print("opts: {}".format(opts))
        for k,v in opts:
            if k in ('-h','--hlep'):
                print("help info")
                sys.exit()
            if k in ('-f','--filename'):
                print('fileinfo:{}'.format(v))
                sys.exit()
            if k in ('-v','--version'):
                print('versionInfo')
                sys.exit()
        
if __name__ == "__main__":
    arg = ArgParser()
    arg.arg_parser()
# python tgetopt.py -f file1
args :[]
opts: [('-f', 'file1')]
fileinfo:file1
# python tgetopt.py --filename f1
args :[]
opts: [('--filename', 'f1')]
fileinfo:f1
# python tgetopt.py -f file1 -h --filename f2 --version q w er 
args :['q', 'w', 'er']
opts: [('-f', 'file1'), ('-h', ''), ('--filename', 'f2'), ('--version', '')]
fileinfo:file1
#
# python tgetopt.py -param p
exceptionoption -p not recognized
Traceback (most recent call last):
  File "tgetopt.py", line 9, in arg_parser
    opts, args = getopt.getopt(sys.argv[1:], "-h-f:-v", ['help','filename=','version'])
  File "/root/miniconda/envs/python36/lib/python3.6/getopt.py", line 95, in getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  File "/root/miniconda/envs/python36/lib/python3.6/getopt.py", line 195, in do_shorts
    if short_has_arg(opt, shortopts):
  File "/root/miniconda/envs/python36/lib/python3.6/getopt.py", line 211, in short_has_arg
    raise GetoptError(_('option -%s not recognized') % opt, opt)
getopt.GetoptError: option -p not recognized

argparse

argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

prog.py

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

 当使用适当的参数运行时,它会输出命令行传入整数的总和或者最大值:

# python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)
# python prog.py 1 2 3 4
4
# python prog.py 1 2 3 4 --sum
10

如果传入无效参数,则会报出错误:

# python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

详细参考: argparse --- 命令行选项、参数和子命令解析器 — Python 3.10.1 文档