5

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
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 41,580
  • 88
  • 260
  • 469

2 Answers2

4

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
  • 497,756
  • 71
  • 530
  • 681
Maxym
  • 659
  • 5
  • 11
  • Well, in this context this python script is to be used to setup the environment for something else. – Alex Sep 13 '14 at 12:04
0

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

Community
  • 1
  • 1
Michael Jaros
  • 4,586
  • 1
  • 22
  • 39