export/set 环境变量读取对应配置

2022-07-17 10:08:54 浏览数 (1)

我们有时候不希望将配置参数写在代码里,而作为单独的文件传入

一种办法是设置环境变量参数,根据这个参数来决定读取哪个配置文件

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/7/6 18:03
# @Author : Michael
# @File : os_environ.py
# @desc :
import os

def get_env_filename():
    srv = os.environ.get('cnf') # 通过环境变量参数读取相关配置
    if srv not in ['online', 'sim', 'qa']:
        raise Exception(f'config error: {srv}')
    return f'.env_{srv}'  # 配置文件名字

if __name__ == '__main__':
    print(get_env_filename())
  • window set varname=val
代码语言:javascript复制
D:gitcodePython_learningmyNote>set cnf=online
D:gitcodePython_learningmyNote>echo %cnf%
online
D:gitcodePython_learningmyNote>python os_environ.py
.env_online

D:gitcodePython_learningmyNote>set cnf=on
D:gitcodePython_learningmyNote>python os_environ.py
Traceback (most recent call last):
  File "os_environ.py", line 15, in <module>
    print(get_env_filename())
  File "os_environ.py", line 11, in get_env_filename
    raise Exception(f'config error: {srv}')
Exception: config error: on
  • linux export varname=val
代码语言:javascript复制
(base) /mnt/d/gitcode/Python_learning/myNote$ export cnf=online
(base) /mnt/d/gitcode/Python_learning/myNote$ echo $cnf
online
(base) /mnt/d/gitcode/Python_learning/myNote$ python os_environ.py
.env_online

(base)  /mnt/d/gitcode/Python_learning/myNote$ export cnf=on
(base)  /mnt/d/gitcode/Python_learning/myNote$ echo $cnf
on
(base)  /mnt/d/gitcode/Python_learning/myNote$ python os_environ.py
Traceback (most recent call last):
  File "os_environ.py", line 15, in <module>
    print(get_env_filename())
  File "os_environ.py", line 11, in get_env_filename
    raise Exception(f'config error: {srv}')
Exception: config error: on

0 人点赞