environment.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import subprocess
  3. import logging
  4. logger = logging.getLogger(__name__)
  5. def setup_environment():
  6. """
  7. 加载 /etc/profile.d/invo.sh 的环境变量到当前 Python 进程。
  8. 同时设置 ulimit -n 4096 和 PYTHONUNBUFFERED=1。
  9. """
  10. _source_shell_script("/etc/profile.d/invo.sh")
  11. _set_resource_limits()
  12. os.environ['PYTHONUNBUFFERED'] = '1'
  13. os.environ.setdefault('LESSCHARSET', 'utf-8')
  14. def _source_shell_script(script_path: str):
  15. """执行 source <script> && env,将结果合并到 os.environ"""
  16. if not os.path.isfile(script_path):
  17. logger.warning(f"Shell script not found: {script_path}")
  18. return
  19. cmd = f"bash -c 'source {script_path} && env'"
  20. try:
  21. output = subprocess.check_output(cmd, shell=True, stderr=subprocess.PIPE,
  22. universal_newlines=True)
  23. except subprocess.CalledProcessError as e:
  24. logger.error(f"Failed to source {script_path}: {e.stderr}")
  25. raise
  26. for line in output.splitlines():
  27. key, _, value = line.partition('=')
  28. if key:
  29. os.environ[key] = value
  30. def _set_resource_limits():
  31. """ulimit -n 4096"""
  32. try:
  33. import resource
  34. soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
  35. resource.setrlimit(resource.RLIMIT_NOFILE, (4096, hard))
  36. logger.info("File descriptor limit set to 4096")
  37. except ValueError:
  38. logger.warning("Could not set file descriptor limit")