Setting environment variables for the curent termial session through python

Viewed 600

I am trying to write a python script that sets environment variables based on user input. I can set env variables manually in the terminal by typing the regular export myVar='value'. If i type echo $myVar i get the result 'value'. All good so far.

I have this script:

import os
os.environ['myVar'] = 'value'

If i print the variable inside the python session i see the variable. But if i exit python and just do the same echo $myVar i dont see the variable. Ok so the variable is only part of the current python session, its not actually executed in the terminal so i tried something else:

import os
os.system('export myVar=value')

this also does nothing. I dont get the varialbe in the terminal.

For example if i try this:

import os
os.system('gedit')

i get gedit started. So os.system works. But why it doesnt want to set a variable?

I thought this is a python limitation os i tried bashcript

echo "Setting variable"
export myVar='value'

saved this as a var.sh, made it executable with chmod +x and ran it with ./var.sh Still nothing. There is no variable set. Its strange, if i type the same thing in the terminal directly it works, but not through a bash script. I also saw somewhere that you have to source it first. So i created another bash script like this:

source var.sh
echo $myVar

Still no variable set. What am i missing here?

I am using python3.8.5 on popOS 20.04

Thanks!

2 Answers

What you are missing is an understanding of the UNIX process model. In UNIX like operating systems (which includes Linux) certain attributes are associated with a specific process, such as your interactive shell. Those attributes include things like the CWD (current working directory) and environment variables. A process cannot directly change the attributes (e.g., the env vars) of a different process. When you start a new process it normally inherits a copy of the env vars of the current process. So when you run your Python program a new process is started. When you modify the env vars of that process it does not affect the env vars of its parent process (your shell). Env vars are not "global". What you're trying to do is impossible by definition.

You can set it within a script, but you wouldn't see it's effects from within that script. https://www.howtogeek.com/668503/how-to-set-environment-variables-in-bash-on-linux

#! /usr/bin/env python3
import os

os .system( 'echo MYVAR=value >> ~/.bashrc' )
os .system( 'exec bash' )

You will see it afterward from the commandline, if that's what you're going for.

echo $MYVAR

value

to revert:

os .system( "sed -i '/MYVAR=/d' ~/.bashrc" )
os .system( 'unset MYVAR' )
Related