Python 和环境变量 [英] Python and environment variables

查看:48
本文介绍了Python 和环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码片段(旨在在 init.d 环境中工作)中,我想执行 test.ClassPath.但是,我在设置和传递用户的 .bashrc 中定义的 CLASSPATH 环境变量时遇到问题.

In the following code snippet (meant to work in an init.d environment) I would like to execute test.ClassPath. However, I'm having trouble setting and passing the CLASSPATH environment variable as defined in the user's .bashrc.

这是我沮丧的根源:

  • 当以下脚本在使用模式下运行时,它会打印出 CLASSPATH OK(来自 $HOME/.bashrc)
  • 当我以 root 身份运行它时,它也可以正常显示 CLASSPATH(我已经使用 CLASSPATH 设置了/etc/bash.bashrc)
  • 但是,当我执行sudo script.py"(以模拟 init.d 启动时发生的情况)时,缺少 CLASSPATH !!

CLASSPATH 非常大,所以我想从一个文件中读取它......比如 $HOME/.classpath

The CLASSPATH is quite large, so I'd like to read it from a file .. say $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()

推荐答案

您可以在启动 python 脚本之前放置 source ~/.bashrc 来设置环境变量.

You could put source ~/.bashrc before starting your python script to get the environment variables set.

这篇关于Python 和环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆