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 @chepner
s 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
Beautiful Soup Findall Doesn't Find Them All
What Do I Need to Read Microsoft Access Databases Using Python
Os.Walk Without Hidden Folders
List of Lists Changes Reflected Across Sublists Unexpectedly
What Is Truthy and Falsy? How Is It Different from True and False
Finding the Index of an Item in a List
Adding a Method to an Existing Object Instance
How Are Iloc and Loc Different
How to Remove Script Tags With Beautifulsoup
Process List on Linux Via Python
Simulating Key Press Event Using Python For Linux
Relative Imports For the Billionth Time
Accessing the Index in 'For' Loops