python如何获取环境变量(转)

转载请注明出处:python—读取环境变量

python中经常会通过环境变量来进行参数传递和环境配置。

本章记录读取环境变量的方案

设置环境变量

首先设置环境变量

  1. $ export ENV_PORT=3333
  2. $ echo $ENV_PORT
  3. 3333

方案一 os读取

os直接读取

使用os获取环境变量字典

  1. import os
  2. os.getenv('ENV_PORT')
  3. os.environ.get('ENV_PORT')
  4. os.environ['ENV_PORT']

打印所有环境变量,遍历字典

  1. import os
  2. env_dist = os.environ # environ是在os.py中定义的一个dict environ = {}
  3. for key in env_dist:
  4. print key + ' : ' + env_dist[key]

通过文件中转环境变量

方法如下:

  1. import os
  2. import ConfigParser
  3. cf = ConfigParser.ConfigParser()
  4. cf.read('test.conf')
  5. def resolveEnv(con):
  6. if con.startswith('ENV_'):
  7. return os.environ.get(con)
  8. return con
  9. def main():
  10. host = resolveEnv(cf.get('db', 'host'))
  11. port = resolveEnv(cf.get('db', 'port'))
  12. print 'host:%s' % host
  13. print 'port:%s' % port
  14. if __name__ == "__main__":
  15. main()

查看一下配置文件:

  1. $ cat test.conf
  2. [db]
  3. host = 1.2.3.4
  4. port = ENV_PORT

读取配置文件:

  1. $ python test.py
  2. host:1.2.3.4
  3. port:3333

方案二pyhocon

pyhocon是一个python的配置管理库

pyhocon的一个作用是可以直接在配置文件中使用${}的方式引用,pyhocon解析时会自动实现如上resolveEnv的逻辑,对应环境变量。

官网如下:
https://github.com/chimpler/pyhocon

配置文件如下:
default.conf

  1. databases {
  2. # MySQL
  3. active = true
  4. enable_logging = false
  5. resolver = null
  6. # you can use substitution with unquoted strings. If it it not found in the document, it defaults to environment variables
  7. home_dir = ${HOME} # you can substitute with environment variables
  8. "mysql" = {
  9. host = "abc.com" # change it
  10. port = 3306 # default
  11. username: scott // can use : or =
  12. password = tiger, // can optionally use a comma
  13. // number of retries
  14. retries = 3
  15. }
  16. }

${HOME}在解析使用解析时会自动获取到环境变量中的HOME

使用方式

    1. from pyhocon import ConfigFactory
    2. conf = ConfigFactory.parse_file('samples/database.conf')
    3. host = conf.get_string('databases.mysql.host')
    4. same_host = conf.get('databases.mysql.host')
    5. same_host = conf['databases.mysql.host']
    6. same_host = conf['databases']['mysql.host']
    7. port = conf['databases.mysql.port']
    8. username = conf['databases']['mysql']['username']
    9. password = conf.get_config('databases')['mysql.password']
    10. password = conf.get('databases.mysql.password', 'default_password') # use default value if key not found
原文地址:https://www.cnblogs.com/Cody-map-01/p/13994198.html