[英]Python and environment variables
In the following code snippet (meant to work in an init.d environment) I would like to execute test.ClassPath. 在以下代码片段(旨在在init.d环境中工作)中,我想执行test.ClassPath。 However, I'm having trouble setting and passing the CLASSPATH environment variable as defined in the user's .bashrc.
但是,我在设置和传递用户.bashrc中定义的CLASSPATH环境变量时遇到了麻烦。
Here is the source of my frustration: 这是我沮丧的根源:
The CLASSPATH is quite large, so I'd like to read it from a file .. say $HOME/.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()
sudo
will not pass environment variables by default. sudo
默认不会传递环境变量。 From the man page: 从手册页:
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.
There are a few ways of addressing this. 有几种解决方法。
You can edit /etc/sudoers
to explicitly pass the CLASSPATH
variable using the env_keep
configuration directive. 您可以编辑
/etc/sudoers
以使用env_keep
配置指令显式传递CLASSPATH
变量。 That might look something like: 可能看起来像:
Defaults env_keep += "CLASSPATH"
You can run your command using the env
command, which lets you set the environment explicitly. 您可以使用
env
命令运行命令,该命令可让您显式设置环境。 A typical command line invocation might look like this: 典型的命令行调用可能如下所示:
sudo env CLASSPATH=/path1:/path2 java test.ClassPath
The obvious advantage to option (2) is that it doesn't require mucking about with the sudoers
configuration. 选项(2)的明显优点是,它不需要使用
sudoers
配置。
您可以在启动python脚本之前放置source ~/.bashrc
,以设置环境变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.