Python子进程readline()挂起

Python子进程readline()挂起

我试图完成的任务是流一个ruby文件并打印出输出。(:我不想一下子把所有的东西都打印出来)

Main.py

from subprocess import Popen, PIPE, STDOUTimport ptyimport os

file_path = '/Users/luciano/Desktop/ruby_sleep.rb'command = ' '.
join(["ruby", file_path])master, slave = pty.openpty()proc = Popen(command, bufsize=0, shell=True, stdout=slave, stderr=slave, 
close_fds=True)     stdout = os.fdopen(master, 'r', 0)while proc.poll() is None:
    data = stdout.readline()
    if data != "":
        print(data)
    else:
        breakprint("This is never reached!")

红宝石睡眠

puts "hello"sleep 2puts "goodbye!"

问题

流文件很好。打个招呼/再见的输出是用2秒的延迟打印出来的。正如脚本应该工作的那样。问题是readline()挂起,永远不会退出。我从来没有达到最后的指纹。

我知道这里有很多这样的问题,堆积如山,但没有一个问题让我解决了这个问题。我不喜欢整个子过程,所以请给我一个更多的手/具体的答案。

问候

编辑

修复意外代码。(与实际错误无关)



冉冉说
浏览 900回答 3
3回答

胡子哥哥

不确定您的代码有什么问题,但以下几点似乎适用于我:#!/usr/bin/pythonfrom subprocess import Popen, PIPEimport threading p = Popen('ls', stdout=PIPE)class ReaderThread(threading.Thread):     def __init__(self, stream):         threading.Thread.__init__(self)         self.stream = stream    def run(self):         while True:             line = self.stream.readline()             if len(line) == 0:                 break             print line,reader = ReaderThread(p.stdout)reader.start()# Wait until subprocess is donep.wait()             # Wait until we've processed all outputreader.join()print "Done!"请注意,我没有安装Ruby,因此无法检查您的实际问题。工作得很好ls尽管如此。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python