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 can't change your shell's environment from a child process (such as Python), it's just not possible.

Here's what's happening when you try os.system('export MY_DATA="my_export"')...

/bin/bash process, command `python yourscript.py` 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 it's discarded, along with the environment that you have just changed.

Export a variable from bash and use it in Python

To use environment variables from your python script you need to call:

import os
os.environ['test_var']

os.environ is a dictionary with all the environment variables, you can use all the method a dict has. For instance, you could write :

os.environ.get('test_var', 'default_value')

how to save data via export in python program?

Thanks to @chepners comment, the solution was using $() instead of using export.

As it's mentioned in comments :

export only passes information from a parent to a child process, not the other direction.

So one of the correct ways to get an output from other application within your script is as follows:

output=$(python test.py arg1 arg2 arg3)


Related Topics



Leave a reply



Submit