Alex
Alex

Reputation: 44395

How to set a environment variable in the current shell with Python?

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?

Upvotes: 7

Views: 5185

Answers (2)

Michael Jaros
Michael Jaros

Reputation: 4681

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

Upvotes: 1

Maxym
Maxym

Reputation: 679

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.

Upvotes: 5

Related Questions