简体   繁体   English

Bash正在等待python子进程

[英]Bash is waiting for a python subprocess

I have three scripts which call each other. 我有三个互相调用的脚本。 They are the followings: 它们是以下内容:

script1.sh: script1.sh:

s=`./script2.py`;
echo "DONE";

script2.py: script2.py:

#!/usr/bin/env python3
import subprocess

subprocess.Popen(["./script3.py"])
print ("Exit script2")

script3.py: script3.py:

#!/usr/bin/env python3
import time

time.sleep(20)
print ("child OK")

Unfortunatelly the script1.sh is a third-party software and I cannot modify that. 不幸的是,script1.sh是第三方软件,我无法对其进行修改。

The script2.py launch the script3.py in the background and exit. script2.py在后台启动script3.py并退出。 It works well from the command line. 它在命令行中运行良好。 But when the the script1.sh call the script2.py that is waiting for the script3.py. 但是当script1.sh调用正在等待script3.py的script2.py时。 So, the script1.sh is freezing. 因此,script1.sh已冻结。 How can I avoid it? 我该如何避免呢?

The problem is that script1.sh is capturing stdout and python has not finished writing to stdout until script3.py finishes. 问题在于script1.sh正在捕获stdout,而python在script3.py完成之前还没有完成向stdout的写入。

One solution is to send the stdout of script3.py somewhere else. 一种解决方案是将script3.py的标准输出发送到其他地方。 For example, this allows script1.sh to complete quickly: 例如,这允许script1.sh快速完成:

$ cat script2.py 
#!/usr/bin/env python3
import subprocess
import sys

subprocess.Popen(["./script3.py"], stdout=sys.stderr)
print ("Exit script2")

With this change, script1.sh exits quickly and, much later, child OK appears on the terminal. 进行此更改后, script1.sh迅速退出,并且很久以后,在终端上会出现child OK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM