在解析程序参数时,我希望能够在未指定为程序参数的情况下从环境中获取某些参数。
我目前的代码如下:
parser = argparse.ArgumentParser(
description="Foo Bar Baz")
parser.add_argument('--metadata-api-user', type=str,
help='Username for basic authentication access to the metadata API. If not given, will be extracted from env variable {}'.format("API_USER"),
default=os.environ.get("API_USER"))
parser.add_argument('--metadata-api-password', type=str,
help='Password for basic authentication access to the metadata API. If not given, will be extracted from env variable {}'.format("API_PASS"),
default=os.environ.get("API_PASS"))
parser.add_argument('--version', type=int, help='Version number', default=1)
parser.add_argument('--location', type=str, help='Location to place thing (default: ./)',default="./")
args = parser.parse_args(args)
这提供了我想要的功能,但如果没有给定env变量并且也没有在命令行中给出,我希望argparse会引发ArgumentError。
如果仅在命令行中指定并未在环境变量中指定,则environ[keyname]在创建参数时将引发keyerror,这并不理想。
在创建参数时设置类似“allow-none'=false”的参数将是很好的选择,但如果有其他解决方案那就太棒了。
default
为None
时,将参数设为必需。 - Eric