只能将环境变量从父进程传递到子进程。在
当创建子进程时,环境块被复制到子进程-子进程有一个副本,因此子进程中的任何更改只会影响子进程的副本(以及它创建的任何其他子进程)。在
要与父级通信,最简单的方法是在bash中使用命令替换,在bash中我们捕获stdout:
Bash脚本:#!/bin/bash
var=$(python myPythonScript.py)
echo "Value in bash: $var"
Python脚本:
^{pr2}$
样本运行:$ bash gash.sh
Value in bash: Hollow world!
如果python中有其他print语句,则只需要过滤出所需的数据,可能的方法是用众所周知的前缀标记数据。在
如果python中有许多print语句,则此解决方案不可伸缩,因此可能需要使用进程替换,如下所示:
Bash脚本:#!/bin/bash
while read -r line
do
if [[ $line = ++++* ]]
then
# Strip out the marker
var=${line#++++}
else
echo "$line"
fi
done <
echo "Value in bash: $var"
Python脚本:def someFunc():
return "Hollow World"
print("Running some code...")
VarFromFirstScript = someFunc()
# Prefix our data with a well-known marker
print("++++" + VarFromFirstScript)
print("Now I do other stuff")
样本运行:$ bash gash.sh
Running some code...
Now I do other stuff
Value in bash: Hollow World