Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Persistent shell variables in subprocess

I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.

Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?

like image 317
PeterBelm Avatar asked Jul 14 '09 15:07

PeterBelm


2 Answers

subprocess.Popen takes an optional named argument env that's a dictionary to use as the subprocess's environment (what you're describing as "shell variables"). Prepare a dict as you need it (you may start with a copy of os.environ and alter that as you need) and pass it to all the subprocess.Popen calls you perform.

like image 192
Alex Martelli Avatar answered Sep 21 '22 04:09

Alex Martelli


Alex is absolutely correct. To give an example

current_env=environ.copy()
current_env["XXX"] = "SOMETHING" #If you want to change some env variable
subProcess.Popen("command_n_args", env=current_env)
like image 44
Siva Avatar answered Sep 23 '22 04:09

Siva