| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- import os
- import subprocess
- import logging
- logger = logging.getLogger(__name__)
- def setup_environment():
- """
- 加载 /etc/profile.d/invo.sh 的环境变量到当前 Python 进程。
- 同时设置 ulimit -n 4096 和 PYTHONUNBUFFERED=1。
- """
- _source_shell_script("/etc/profile.d/invo.sh")
- _set_resource_limits()
- os.environ['PYTHONUNBUFFERED'] = '1'
- os.environ.setdefault('LESSCHARSET', 'utf-8')
- def _source_shell_script(script_path: str):
- """执行 source <script> && env,将结果合并到 os.environ"""
- if not os.path.isfile(script_path):
- logger.warning(f"Shell script not found: {script_path}")
- return
- cmd = f"bash -c 'source {script_path} && env'"
- try:
- output = subprocess.check_output(cmd, shell=True, stderr=subprocess.PIPE,
- universal_newlines=True)
- except subprocess.CalledProcessError as e:
- logger.error(f"Failed to source {script_path}: {e.stderr}")
- raise
- for line in output.splitlines():
- key, _, value = line.partition('=')
- if key:
- os.environ[key] = value
- def _set_resource_limits():
- """ulimit -n 4096"""
- try:
- import resource
- soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
- resource.setrlimit(resource.RLIMIT_NOFILE, (4096, hard))
- logger.info("File descriptor limit set to 4096")
- except ValueError:
- logger.warning("Could not set file descriptor limit")
|