如何使 argparse 将所有参数视为位置参数?
How to make argparse treat all arguments as positional?
如何让 argparse 解析器将所有参数都视为 位置,甚至那些看起来像选项的参数?例如,使用此定义:
parser.add_argument('cmd', nargs='*', help='The command to run')
我希望能够运行
prog.py mycomand --foo arg
并将 ['mycomand', '--foo', 'arg']
捕获为 cmd
参数。
原来我只需要将 nargs='*'
替换为 nargs=argparse.REMAINDER
。来自 docs:
argparse.REMAINDER
All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.
这也可以,但不太方便:
prog.py mycomand -- --foo arg
如何让 argparse 解析器将所有参数都视为 位置,甚至那些看起来像选项的参数?例如,使用此定义:
parser.add_argument('cmd', nargs='*', help='The command to run')
我希望能够运行
prog.py mycomand --foo arg
并将 ['mycomand', '--foo', 'arg']
捕获为 cmd
参数。
原来我只需要将 nargs='*'
替换为 nargs=argparse.REMAINDER
。来自 docs:
argparse.REMAINDER
All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.
这也可以,但不太方便:
prog.py mycomand -- --foo arg