getopts在python中的行为异常

2024-04-20 12:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
1条回答
网友
1楼 · 发布于 2024-04-20 12:51:53
import argparse

argParser = argparse.ArgumentParser()
argParser.add_argument(
        '-p', ' present', dest='present', help='write help here for this parameter')

args = argParser.parse_args()

if args.present:
    search(a)

使用argparse的示例代码,它更易于管理和使用 -h(或)help是argparse的内置选项

如果您想使用getopt,请参阅文档来解析选项

https://docs.python.org/2/library/getopt.html

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

相关问题 更多 >