Aaron Schif
Aaron Schif

Reputation: 2442

Using Python change Environment Variables

I am having a problem with the environment variables in python. How do I get python to export variables to the parent shell?

I am using ubuntu, python 2.7.4

I get this:

$ python
>>> import os
>>> os.environ
{'HOME':'~'}
>>> os.environ['foo']='bar'
>>> os.environ
{'HOME':'~','foo':'bar'}
>>> quit()
$ echo $foo
    # Place #1
$ python
>>> import os
>>> os.environ
{'HOME':'~'}    # Place #2
>>> 

My expected output is:

Thanks

Upvotes: 3

Views: 1777

Answers (1)

user2246674
user2246674

Reputation: 7719

Environment variables set in a child process (e.g. python) do not affect the parent process.

It's a one-way street; if this could be done it would be very easy to exploit shells! The environment variables must be set in the parent process itself. This restriction is enforced by the operating system and is not specific to Python.

Note that sourcing a file in a shell (e.g. . script.sh) doesn't create a new process; but there is no way to "source" Python files.

Upvotes: 4

Related Questions