Setting options from environment variables when using argparse

后端 未结 12 1992
执念已碎
执念已碎 2020-12-08 04:06

I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, a

12条回答
  •  粉色の甜心
    2020-12-08 04:52

    You can set the default= of the argument to a .get() of os.environ with the environment variable you want to grab.

    You can also pass a 2nd argument in the .get() call, which is the default value if .get() doesn't find an environment variable by that name (by default .get() returns None in that case).

    import argparse
    import os
    
    parser = argparse.ArgumentParser(description='test')
    parser.add_argument('--url', default=os.environ.get('URL'))
    
    args = parser.parse_args()
    if not args.url:
        exit(parser.print_usage())
    

提交回复
热议问题