jmd*_*_dk 3 python parsing command-line-arguments argparse python-3.x
我正在使用Python的argparse模块来解析命令行参数。考虑下面的简化示例,
# File test.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store')
parser.add_argument('-a', action='append')
args = parser.parse_args()
print(args)
Run Code Online (Sandbox Code Playgroud)
可以成功地称为
python test.py -s foo -a bar -a baz
Run Code Online (Sandbox Code Playgroud)
每个参数-s前后都需要一个参数-a,如果使用引号,则参数可以包含空格。但是,如果参数以破折号(-)开头且不包含任何空格,则代码将崩溃:
python test.py -s -begins-with-dash -a bar -a baz
Run Code Online (Sandbox Code Playgroud)
错误:参数-s:预期一个参数
我知道它被解释-begins-with-dash为新选项的开始,这是非法的,因为-s尚未收到其必需的参数。尽管-begins-with-dash还没有定义带有名称的选项,但也很清楚,因此它不应该首先将其解释为选项。如何使argparse一个或多个前导破折号接受参数?
小智 6
您可以通过包含等号来强制argparse将参数解释为值:
python test.py -s=-begins-with-dash -a bar -a baz
Namespace(a=['bar', 'baz'], s='-begins-with-dash')