使用argparse获取命令行参数

时间:2016-01-26 09:54:44

标签: python bash python-2.7 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"

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

The standard documentation未提及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的内容,以检查提供的文件是否实际上是预期格式的JSON等,但这似乎超出了问题的范围。

相关问题