7

I want to set an environment variable with a Python script, influencing the shell I am starting the script in. Here is what I mean

python -c "import os;os.system('export TESTW=1')"

But the command

echo ${TESTW}

returns nothing. Also with the expression

python -c "import os;os.environ['TEST']='1'"

it does not work.

Is there another way to do this in the direct sense? Or is it better to write the variables in a file which I execute from 'outside' of the Python script?

Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
asked Sep 13, 2014 at 11:55

2 Answers 2

5

You can influence environment via: putenv BUT it will not influence the caller environment, only environment of forked children. It's really much better to setup environment before launching the python script.

I may propose such variant. You create a bash script and a python script. In bash script you call the python script with params. One param - one env variable. Eg:

#!/bin/bash
export TESTV1=$(python you_program.py testv1)
export TESTV2=$(python you_program.py testv2)

and you_program.py testv1 returns value just for one env variable.

chepner
537k77 gold badges592 silver badges744 bronze badges
answered Sep 13, 2014 at 12:02

1 Comment

Well, in this context this python script is to be used to setup the environment for something else.
1

I would strongly suggest using the solution proposed by chepner and Maxym (where the Python script provides the values and your shell exports the variables). If that is not an option for you, you could still use eval to execute what the python script writes in your current Bash process:

eval $( python -c "print('export TESTW=1')" )

Caution: eval is usually read "evil" in Bash programming. As a general rule of thumb, one should avoid "blindly" executing code that is not fully under one's control. That includes being generated by another program at runtime as in this case. See also Stack Overflow question Why should eval be avoided in Bash, and what should I use instead? .

answered Sep 13, 2014 at 13:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.