简体   繁体   English

Python和环境变量

[英]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: 这是我沮丧的根源:

  • When the below script is run in use mode, it prints out the CLASSPATH OK (from $HOME/.bashrc) 在使用模式下运行以下脚本时,它会打印出CLASSPATH OK(从$ HOME / .bashrc开始)
  • when I run it as root, it also displays CLASSPATH fine (I've set up /etc/bash.bashrc with CLASSPATH) 当我以root身份运行它时,它也显示CLASSPATH很好(我已经用CLASSPATH设置了/etc/bash.bashrc)
  • BUT when I do "sudo script.py" (to simulate what happens at init.d startup time), the CLASSPATH is missing !! 但是,当我执行“ sudo script.py”(模拟init.d启动时发生的情况)时,CLASSPATH丢失了!

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. 有几种解决方法。

  1. 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" 
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM