Search code examples
pythonlinuxbashenvironment-variableswindows-subsystem-for-linux

Set python variable as env variable in linux


I have a variable TOTAL_PROCESSED that defined in python script. I want to set this variable from python code as environment variable in WSL. So that after python script execution I was able to echo $TOTAL_PROCESSED and see the value passed from python.

I found an os command:

Set environment variables

os.environ['TOTAL_PROCESSED'] = 'some-value' or os.environ.setdefault('TOTAL_PROCESSED', 'some-value').

However, after script execution I wasn`t able to echo this variable.

Can someone help me to set value from python script as env variable in Linux?


Solution

  • Environment variables are usually given to child process from its parent and not the other way around.

    Why is it not working : When you start your python script it inherits its own environment from the parent process ( the shell ), then you modify this environment and when the script ends its environment is destroyed along with the python process. So you modified the child environment not your shell's environment.

    Workaround : Try another way of passing data, writing to a file or returning output from the script maybe.

    To illustrate :

    script.py

    TOTAL_PROCESSED = 0
    
    # ...
    # Processing part
    # ...
    # ( TOTAL_PROCESSED = 50 )
    
    with open("totalprocessed", "w+") as f:
        f.write(str(TOTAL_PROCESSED))
    

    shell

    python script.py ; export TOTAL_PROCESSED=$(cat totalprocessed)
    

    EDIT: If you really need to change parent environment head here: https://unix.stackexchange.com/a/38212