繁体   English   中英

使用argparse获取命令行参数

[英]Get command line parameters with argparse

我正在尝试使用Python的argparse,但无法获取命令行参数。

这是我的代码:

DEFAULT_START_CONFIG='/tmp/config.json'

parser = argparse.ArgumentParser(description='Start the Cos service and broker for development purposes.')
parser.add_argument('-c', '--config', default=DEFAULT_START_CONFIG, action=FileAction, type=str, nargs='?',
                help='start configuration json file (default:' +  DEFAULT_START_CONFIG + ')')

args = parser.parse_args()

但是当我像这样运行我的python脚本时:

./start.py -c /usr/local/config.json

而不是获取此路径,而是获取定义的默认值( /tmp/config.json )。

print args.config ---> "/tmp/config.json"

我在这里做错了什么?

标准文档没有提到FileAction 相反,有一个FileType类用于type参,而不是用于action

所以我会写这样的东西:

DEFAULT_START_CONFIG='/tmp/config.json'

parser = argparse.ArgumentParser(description='Start the Cos service and broker for development purposes.')
parser.add_argument('-c', '--config', default=DEFAULT_START_CONFIG,
    type=argparse.FileType('r'), help='start configuration json file')
args = parser.parse_args()
print(args)

这给了我以下内容:

$ python test3.py
Namespace(config=<open file '/tmp/config.json', mode 'r' at 0x7fd758148540>)
$ python test3.py -c
usage: test3.py [-h] [-c CONFIG]
test3.py: error: argument -c/--config: expected one argument
$ python test3.py -c some.json
usage: test3.py [-h] [-c CONFIG]
test3.py: error: argument -c/--config: can't open 'some.json': [Errno 2] No such file or directory: 'some.json'
$ touch existing.json
$ python test3.py -c existing.json
Namespace(config=<open file 'existing.json', mode 'r' at 0x7f93e27a0540>)

您可以将argparse.FileType子类JsonROFileType类的东西, JsonROFileType将检查所提供的文件是否实际上是预期格式的JSON等,但这似乎超出了问题的范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM