通过套接字顺序发送subprocess.Popen的stdout

2 投票
1 回答
1713 浏览
提问于 2025-04-17 02:51

我知道这个问题之前已经被回答过很多次,但我在我的情况下还没有找到有效的方法……希望你们能帮帮我。
我想要实时地把Popen调用中的标准输出(stdout)和/或标准错误(stderr)数据输出到一个套接字连接,而不是输出到标准输出(stdout)。所以,sys.stdout.flush()对我来说没用。

data=sok.recv(512) #the command to execute
p = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE stderr=subprocess.PIPE)

#this work.. but not how i spected, if the subprocess ends too fast, i only get the first line
while p.poll() is None:
    sok.send(p.stdout.readline())

#this only send the last line
for i in p.stdout.readline():
    sok.send(i)
    sys.stdout.flush() #why sys.stdout? i don't use it
    p.stdout.flush()   #same result

1 个回答

3

p.poll() 是用来检查一个程序是否还在运行的。如果程序已经结束,它就会返回 false。所以你不应该用这个来检查。

你的代码:

for i in p.stdout.readline():

是读取一行内容,然后逐个字母地处理。这不是你想要的。你应该使用:

for i in p.stdout.readlines():

这样可以返回每一行。

不过,这个方法会在返回任何行之前先把整个文件都读完,可能这也不是你想要的。

所以你应该使用:

for line in p.stdout:

这样可以一行一行地读取,直到没有更多内容可读为止。

撰写回答