How to access environment variable values?

后端 未结 12 1335
孤独总比滥情好
孤独总比滥情好 2020-11-21 23:52

I set an environment variable that I want to access in my Python application. How do I get its value?

相关标签:
12条回答
  • 2020-11-22 00:28

    For django see (https://github.com/joke2k/django-environ)

    $ pip install django-environ
    
    import environ
    env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
    )
    # reading .env file
    environ.Env.read_env()
    
    # False if not in os.environ
    DEBUG = env('DEBUG')
    
    # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
    SECRET_KEY = env('SECRET_KEY')
    
    0 讨论(0)
  • 2020-11-22 00:29

    The original question (first part) was "how to check environment variables in Python."

    Here's how to check if $FOO is set:

    try:  
       os.environ["FOO"]
    except KeyError: 
       print "Please set the environment variable FOO"
       sys.exit(1)
    
    0 讨论(0)
  • 2020-11-22 00:33

    To check if the key exists (returns True or False)

    'HOME' in os.environ
    

    You can also use get() when printing the key; useful if you want to use a default.

    print(os.environ.get('HOME', '/home/username/'))
    

    where /home/username/ is the default

    0 讨论(0)
  • 2020-11-22 00:35

    You can access to the environment variables using

    import os
    print os.environ
    

    Try to see the content of PYTHONPATH or PYTHONHOME environment variables, maybe this will be helpful for your second question. However you should clarify it.

    0 讨论(0)
  • 2020-11-22 00:39

    As for the environment variables:

    import os
    print os.environ["HOME"]
    

    I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.

    0 讨论(0)
  • 2020-11-22 00:39
    import os
    for a in os.environ:
        print('Var: ', a, 'Value: ', os.getenv(a))
    print("all done")
    

    That will print all of the environment variables along with their values.

    0 讨论(0)
提交回复
热议问题