smuggledPancakes
smuggledPancakes

Reputation: 10323

Setting environments variables from a python script

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.

Upvotes: 1

Views: 19265

Answers (3)

Eric Noort
Eric Noort

Reputation: 1

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"

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263307

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).

Upvotes: 1

jcollado
jcollado

Reputation: 40394

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).

Upvotes: 2

Related Questions