我们有时候不希望将配置参数写在代码里,而作为单独的文件传入
一种办法是设置环境变量参数,根据这个参数来决定读取哪个配置文件
# _*_ 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())
D:\gitcode\Python_learning\myNote>set cnf=online
D:\gitcode\Python_learning\myNote>echo %cnf%
online
D:\gitcode\Python_learning\myNote>python os_environ.py
.env_online
D:\gitcode\Python_learning\myNote>set cnf=on
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
(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