在下面的代码片段中(意味着在init.d环境中工作)我想执行test.ClassPath。但是,我在设置和传递用户的.bashrc中定义的CLASSPATH环境变量时遇到了问题。
这是我沮丧的根源:
CLASSPATH非常大,所以我想从文件中读取它...说$ HOME / .classpath
#!/usr/bin/python
import subprocess
import os.path as osp
import os
user = "USERNAME"
logDir = "/home/USERNAME/temp/"
print os.environ["HOME"]
if "CLASSPATH" in os.environ:
print os.environ["CLASSPATH"]
else:
print "Missing CLASSPATH"
procLog = open(osp.join(logDir, 'test.log'), 'w')
cmdStr = 'sudo -u %s -i java test.ClassPath'%(user, ) # run in user
proc = subprocess.Popen(cmdStr, shell=True, bufsize=0, stderr=procLog, stdout=procLog)
procLog.close()
答案 0 :(得分:4)
sudo
不会传递环境变量。从手册页:
By default, the env_reset option is enabled. This causes
commands to be executed with a minimal environment containing
TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER and USERNAME in
addition to variables from the invoking process permitted by
the env_check and env_keep options. This is effectively a
whitelist for environment variables.
有几种解决方法。
您可以修改/etc/sudoers
以明确传递CLASSPATH
使用env_keep
配置指令的变量。那可能
看起来像:
Defaults env_keep += "CLASSPATH"
您可以使用env
命令运行命令,该命令可以显式设置环境。典型的命令行调用可能如下所示:
sudo env CLASSPATH=/path1:/path2 java test.ClassPath
选项(2)的明显优势在于它不需要使用sudoers
配置进行混乱。
答案 1 :(得分:1)
您可以在启动python脚本之前放置source ~/.bashrc
以设置环境变量。