How to use export with Python on Linux

How to use export with Python on Linux

export is a command that you give directly to the shell (e.g. bash), to tell it to add or modify one of its environment variables. You cant change your shells environment from a child process (such as Python), its just not possible.

Heres whats happening when you try os.system(export MY_DATA=my_export)

/bin/bash process, command `python` forks python subprocess
   /usr/bin/python process, command `os.system()` forks /bin/sh subprocess
      /bin/sh process, command `export ...` changes its local environment

When the bottom-most /bin/sh subprocess finishes running your export ... command, then its discarded, along with the environment that you have just changed.

You actually want to do

import os
os.environ[MY_DATA] = my_export

How to use export with Python on Linux

Another way to do this, if youre in a hurry and dont mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. Its not very portable across shells, so YMMV.

$(python -c print export MY_DATA=my_export)

(you can also enclose the statement in backticks in some shells “)

Leave a Reply

Your email address will not be published. Required fields are marked *