Sushant Gupta
Sushant Gupta

Reputation: 1527

Environment variables set from python not visible in shell script

I have a python script which sets environment variables. I am running this python script from a shell script and the expectation is to read the value of environment variables set by the python script.

#Python script - x.py#

import os
os.environ['FRUIT'] = 'APPLE'

#Shell script - x.sh#

python -c "import x"
echo $FRUIT

But that does not seem to be working. Nothing gets printed by the shell script. Can any one please explain why it is so and how to fix this?

Upvotes: 2

Views: 2852

Answers (2)

wombat
wombat

Reputation: 698

As mentioned, You can't really do this because of the process boundary. However, if you absolutely must (and I really don't recommend it), there are hacky way. Here is an example where the author makes the shell into evaluating commands coming from Python which happen to be export commands. It's pretty neat, but really, don't do it. Reconsider if you do this information exchange through environment variables.

Upvotes: 0

kindall
kindall

Reputation: 184375

Environment variables set in your Python script will be visible only from processes launched by the Python script, because that's how environment variables work. You can't chnage environment variables in someone else's process. There is no way to "fix" it because it's that way by design.

Upvotes: 4

Related Questions