使用 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"

我做错了什么?

The standard documentation doesn't mention FileAction. Instead there's a class 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,但这似乎超出了范围的问题。