Setting environments variables from a python script

二次信任 提交于 2020-01-23 17:30:09

问题


I am using c-shell and I am used to using setenv. I need to execute an equivalent command from within a python script. I tried using os.environ['JAVA_HOME'] = "/usr/local/java" which works from the python interpreter, but when my script is executed from the command line, the shell it ran in does reflect the newly set environment variable. Can anybody help, I am new to scripting, I hope I made my question clear.


回答1:


If you're using subprocess.Popen, it should be enough to pass the env parameter to the constructor to whatever you need as a dictionary (you can copy the contents of os.environ and add your own environment variables if you wish).




回答2:


As explained in How to use export with Python on Linux, setting an environment variable within any process (such as your Python script) cannot affect any parent processes (such as the csh process from which you execute the Python script).

What you can do is have your Python script print a setenv command, and then evaluate the output in your shell as a command.

For example:

csh% cat foo.py
#!/usr/bin/python

import os;

os.environ["JAVA_HOME"] = "/usr/local/java"

print "setenv JAVA_HOME", os.environ["JAVA_HOME"]
csh% ./foo.py
setenv JAVA_HOME /usr/local/java
csh% echo $JAVA_HOME 
JAVA_HOME: Undefined variable.
csh% eval `./foo.py` 
csh% echo $JAVA_HOME 
/usr/local/java
csh% 

And you can set up an alias in your ~/.cshrc to do the eval `...`, or just invoke it directly from your .cshrc or .login (depending on just what you're trying to accomplish).




回答3:


I know it is been a while sins this issue, but I solved it a little different. Maybe this ain't even the most beautiful solution, but it works.

I created a shell script called env.sh

#!/bin/tcsh
eval $*

Then in my python script called subprocess.

output = subprocess.Popen(["env.sh", "setenv", "DISPLAY", "remhost:0"], stdout = subprocess.PIPE).communicate()[0].split()

This works for me, don't forget to make the env.sh executable by executing "chmod +x env.sh"



来源:https://stackoverflow.com/questions/8496946/setting-environments-variables-from-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!