gpt4 book ai didi

linux - python subprocess.readline() 在调用另一个 python 脚本时阻塞

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:57 24 4
gpt4 key购买 nike

我一直在尝试使用 subprocess 模块将 python 脚本作为子进程运行,并且遇到了逐行读取输出的问题。

我阅读的文档表明您应该能够使用子进程并在标准输出上调用 readline(),如果我调用的脚本是 bash 脚本,这确实有效。但是,当我运行 python 脚本时,readline() 会阻塞,直到整个脚本完成。

我写了几个测试脚本来重复这个问题。在测试脚本中,我尝试在 python 脚本 (tst.py) 中将 python 脚本 (tst1.py) 作为子进程运行,然后逐行读取 tst1.py 的输出。

tst.py 启动 tst1.py 并尝试逐行读取输出:

#!/usr/bin/env python
import sys, subprocess, multiprocessing, time
cmdStr = 'python ./tst1.py'
print(cmdStr)
cmdList = cmdStr.split()
subProc = subprocess.Popen(cmdList, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

while(1):
# this call blocks until tst1.py has completed, then reads all the output
# it then reads empty lines (seemingly for ever)
ln = subProc.stdout.readline()
if ln:
print(ln)

tst1.py 只是循环打印一条消息: #!/usr/bin/env python 导入时间

if __name__ == "__main__":
x = 0
while(x<20):
print("%d: sleeping ..." % x)
# flushing stdout here fixes the problem
#sys.stdout.flush()
time.sleep(1)
x += 1

如果将tst1.py写成shell脚本tst1.sh:

#!/bin/bash
x=0

while [ $x -lt 20 ]
do
echo $x: sleeping ...
sleep 1
let x++
done

readline() 按预期工作。

经过一番尝试后,我发现可以通过刷新 tst1.py 中的标准输出来解决这种情况,但我不明白为什么需要这样做。我想知道是否有人对此行为有解释?

我正在运行 redhat 4 linux:Linux lb-cbga-05 2.6.9-89.ELsmp #1 SMP 2009 年 4 月 20 日星期一 10:33:05 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

最佳答案

因为如果输出缓冲在某个地方,父进程将看不到它,直到子进程存在,此时输出被刷新并且所有 fd 都被关闭。至于为什么它在没有显式刷新输出的情况下与 bash 一起工作,因为当您在大多数 shell 中键入 echo 时,它实际上会 fork 一个执行 echo 的进程>(它会打印一些东西)并且存在,所以输出也会被刷新。

关于linux - python subprocess.readline() 在调用另一个 python 脚本时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13382272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com