Search code examples
pythonshellsubprocessinter-process-communicat

How to set parent process' shell env from child process


The child process has a value which must be passed onto the parent process. I am using python's subprocess.Popen to do that, but child process's TEMP_VAR is not visible from the parent's shell?

import subprocess
import sys

temp = """variable_val"""
subprocess.Popen('export TEMP_VAR=' + temp + '&& echo $TEMP_VAR', shell=True)
//prints variable_val
subprocess.Popen('echo $TEMP_VAR', shell=True)
//prints empty string

Is there a way to do this interprocess communication without using queues (or) Popen's - stdout/stdin keyword args.


Solution

  • Environment variables are copied from parent to child, they are not shared or copied in the other direction. All export does is make an environment variable in the child, so its children will see it.

    Simplest way is to echo in the child process (I'm assuming it is a shell script) and capture it in python using a pipe.

    Python:

    import subprocess
    
    proc = subprocess.Popen(['bash', 'gash.sh'], stdout=subprocess.PIPE)
    
    output = proc.communicate()[0]
    
    print "output:", output
    

    Bash (gash.sh):

    TEMP_VAR='yellow world'
    echo -n "$TEMP_VAR"
    

    Output:

    output: yellow world