46 lines
2.0 KiB
Python
46 lines
2.0 KiB
Python
import importlib.util
|
|
import sys
|
|
import socket
|
|
import os
|
|
|
|
# 加载 默认配置文件 envar.py 和 本机配置文件 (envar.本机编码.py 例如 envar.lin237.py)
|
|
def load_envar():
|
|
# Get current OS type
|
|
if sys.platform.startswith('win'):
|
|
ostype = 'win'
|
|
elif sys.platform.startswith('darwin'):
|
|
ostype = 'mac'
|
|
elif sys.platform.startswith('linux'):
|
|
ostype = 'lin'
|
|
else:
|
|
ostype = 'other'
|
|
# Get current LAN IP address 获取当前主机的局域网 IP 例如 192.168.168.237
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
s.connect(("8.8.8.8", 80))
|
|
lanip = s.getsockname()[0]
|
|
s.close()
|
|
# Load environment variables
|
|
this_script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
calling_script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) # Get the directory of the calling script
|
|
envFileLocal = os.path.join(calling_script_dir, "envar." + ostype + lanip.split(".")[-1] + ".py") # 本主机配置文件
|
|
envFileDefault = os.path.join(calling_script_dir, "envar.py") # 默认配置文件
|
|
# 总是加载默认配置文件,作为基础配置
|
|
print(f"*** Loading default envar file: {envFileDefault}")
|
|
if not os.path.exists(envFileDefault):
|
|
raise FileNotFoundError("Default envar file not found")
|
|
spec = importlib.util.spec_from_file_location("envar", envFileDefault)
|
|
envar = importlib.util.module_from_spec(spec)
|
|
sys.modules[spec.name] = envar
|
|
spec.loader.exec_module(envar)
|
|
# 如果存在本机配置文件,加载并覆盖默认配置
|
|
if os.path.exists(envFileLocal):
|
|
print(f"*** Loading and merging local envar file: {envFileLocal}")
|
|
spec_local = importlib.util.spec_from_file_location("env_local", envFileLocal)
|
|
env_local = importlib.util.module_from_spec(spec_local)
|
|
spec_local.loader.exec_module(env_local)
|
|
# 合并配置到env中
|
|
for attr in dir(env_local):
|
|
if not attr.startswith('__'):
|
|
setattr(envar, attr, getattr(env_local, attr))
|
|
return envar
|