如何从子进程设置父进程'shell env

时间:2022-10-18 17:52:35

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?

子进程具有必须传递到父进程的值。我使用python的subprocess.Popen来做到这一点,但是父进程的shell中看不到子进程的TEMP_VAR?

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.

有没有办法在不使用队列(或)Popen的 - stdout / stdin关键字args的情况下进行这种进程间通信。

1 个解决方案

#1


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.

最简单的方法是在子进程中回显(我假设它是一个shell脚本)并使用管道在python中捕获它。

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

#1


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.

最简单的方法是在子进程中回显(我假设它是一个shell脚本)并使用管道在python中捕获它。

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