Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use export with Python on Linux

I need to make an export like this in Python :

# export MY_DATA="my_export" 

I've tried to do :

# -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') 

But when I list export, "MY_DATA" not appear :

# export 

How I can do an export with Python without saving "my_export" into a file ?

like image 350
Kevin Campion Avatar asked Oct 01 '09 19:10

Kevin Campion


People also ask

How do I run a Python export command?

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"') …

How do I export in Linux?

In this guide, we will look at the export command in Linux. Export is a built-in command of the Bash shell. It is used to mark variables and functions to be passed to child processes. Basically, a variable will be included in child process environments without affecting other environments.

How do I export in Unix?

The export command is fairly simple to use as it has straightforward syntax with only three available command options. In general, the export command marks an environment variable to be exported with any newly forked child processes and thus it allows a child process to inherit all marked variables.


2 Answers

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.

like image 196
alex tingle Avatar answered Sep 24 '22 06:09

alex tingle


You actually want to do

import os os.environ["MY_DATA"] = "my_export" 
like image 43
Alex Avatar answered Sep 23 '22 06:09

Alex