class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
sys.argv[0]
)ArgumentParser
对象的列表,它们的参数也应包含在内None
)None
)-h/--help
选项(默认值: True
)True
)import argparse
parser = argparse.ArgumentParser(prog="XSniff", description="Capturing Packets According to Network Protocol")
parser.add_argument("-n", type=int, metavar="count", help="positive integer|capture packet count.")
parser.add_argument("-f", type=str, metavar="protocol", help="""
string|protocol you want to filter. ip(Default)
such as ip, udp, tcp or icmp etc...""")
>>> parser.print_help()
usage: XSniff [-h] [-n count] [-f protocol]
Capturing Packets According to Network Protocol
optional arguments:
-h, --help show this help message and exit
-n count positive integer|capture packet count.
-f protocol string|protocol you want to filter. ip(Default) such as ip,
udp, tcp or icmp etc...
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
定义单个的命令行参数应当如何解析:
foo
或 -f, --foo
。parse_args()
所返回对象上的属性名。import argparse
parser = argparse.ArgumentParser(prog="XSniff", description="Capturing Packets According to Network Protocol")
parser.add_argument("-n", type=int, metavar="count", default=None, dest="num", help="positive integer|capture packet count.")
parser.add_argument("-f", type=str, metavar="protocol", default="ip", dest="protocol", help="""
string|protocol you want to filter. ip(Default)
such as ip, udp, tcp or icmp etc...""")
args = parser.parse_args()
num = args.num
protocol = args.protocol
print("Capture {p} packets. Capture Num:{n}".format(p=protocol, n=num if num else "Inf"))
$ python XSniff.py
Capture ip packets. Capture Num:Inf
$ python XSniff.py -f tcp
Capture tcp packets. Capture Num:Inf
$ python XSniff.py -f tcp -n 10
Capture tcp packets. Capture Num:10