python--读取环境变量

2023-01-31 05:01:48 python

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

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

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

首先设置环境变量

$ export ENV_PORT=3333
$ echo $ENV_PORT
3333

os直接读取

使用os获取环境变量字典

import os
os.getenv('ENV_PORT')
os.environ.get('ENV_PORT')
os.environ['ENV_PORT']

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

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

通过文件中转环境变量

方法如下:

import os
import ConfigParser

cf = ConfigParser.ConfigParser()
cf.read('test.conf')

def resolveEnv(con):
    if con.startswith('ENV_'):
        return os.environ.get(con)
    return con

def main():
    host = resolveEnv(cf.get('db', 'host'))
    port = resolveEnv(cf.get('db', 'port'))

    print 'host:%s' % host
    print 'port:%s' % port

if __name__ == "__main__":
    main()

查看一下配置文件:

$ cat test.conf
[db]
host = 1.2.3.4
port = ENV_PORT

读取配置文件:

$ python test.py
host:1.2.3.4
port:3333

pyhocon是一个python的配置管理库

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

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

配置文件如下:
default.conf

  databases {
    # Mysql
    active = true
    enable_logging = false
    resolver = null
    # you can use substitution with unquoted strings. If it it not found in the document, it defaults to environment variables
    home_dir = ${HOME} # you can substitute with environment variables
    "mysql" = {
      host = "abc.com" # change it
      port = 3306 # default
      username: scott // can use : or =
      passWord = tiger, // can optionally use a comma
      // number of retries
      retries = 3
    }
  }

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

使用方式

from pyhocon import ConfigFactory

conf = ConfigFactory.parse_file('samples/database.conf')
host = conf.get_string('databases.mysql.host')
same_host = conf.get('databases.mysql.host')
same_host = conf['databases.mysql.host']
same_host = conf['databases']['mysql.host']
port = conf['databases.mysql.port']
username = conf['databases']['mysql']['username']
password = conf.get_config('databases')['mysql.password']
password = conf.get('databases.mysql.password', 'default_password') #  use default value if key not found

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

相关文章