Setting options from environment variables when using argparse

后端 未结 12 2013
执念已碎
执念已碎 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:32

    There is an example use-case for ChainMap where you merge together defaults, environment variables and command line arguments.

    import os, argparse
    
    defaults = {'color': 'red', 'user': 'guest'}
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--user')
    parser.add_argument('-c', '--color')
    namespace = parser.parse_args()
    command_line_args = {k:v for k, v in vars(namespace).items() if v}
    
    combined = ChainMap(command_line_args, os.environ, defaults)
    

    Came to me from a great talk about beautiful and idiomatic python.

    However, I'm not sure how to go about the difference of lower- and uppercase dictionary keys. In the case where both -u foobar is passed as an argument and environment is set to USER=bazbaz, the combined dictionary will look like {'user': 'foobar', 'USER': 'bazbaz'}.

提交回复
热议问题