0

I need to execute several shell scripts with python, some scripts would export environment parameters, so I need to execute them in the same process, otherwise, other scripts can't see the new environment parameters

in one word, I want to let the shell script change the environment of the python process so I should not use subprocess, any idea how to realize it?

2
  • It's simple: You can't. (Unless you implement a shell script interpreter in Python.) Commented Apr 14, 2015 at 7:12
  • I guess so, just want to double confirm Commented Apr 14, 2015 at 7:30

2 Answers 2

1

What if you make a 'master' shell script that would execute all the others in sequence? This way you'll only have to create a single sub-process yourself, and the individual scripts will share the same environment.

If, however, you would like to interleave script executions with Python code, then you would probably have to make each of the scripts echo its environment to stdout before exiting, parse that, and then pass it into the next script (subprocess.Popen() accepts the env parameter, which is a map.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your quick response, what if I want to let the scripts able to change the python environment? are there any ways to realize it?
Then, again, you would probably want the scripts to echo their current environment variables to stdout, parse the output in Python, and add the variables to the os.environ map.
Yes, that might be a solution, thanks
1

No, you cannot run more than one program (bash, python) in the same process at the same time.

But you can run them in sequence using exec in bash or one of the exec commands in python, like os.execve. Several things survive the "exec boundary", one of which is the environment block. So in each bash script you exec the next, and finally exec your python.

You might also consider using an IPC mechanism like a named pipe to pass data between processes.

I respectfully suggest that you look at your design again. Why are you mixing bash and python? Is it just to reuse code? Even if you managed this you will end with a real mess. It is generally easier to stick with one language.

2 Comments

Thanks, the tool is written with python, but I want to let users able to use shell
@Jan: OK, so you should use an IPC mechanism. The bottom line is that you cannot embed bash in python right now. Maybe you should upgrade your users to python :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.