Python子进程readline()挂起我试图完成的任务是流一个ruby文件并打印出输出。(注:我不想一下子把所有的东西都打印出来)Main.pyfrom 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()挂起,永远不会退出。我从来没有达到最后的指纹。我知道这里有很多这样的问题,堆积如山,但没有一个问题让我解决了这个问题。我不喜欢整个子过程,所以请给我一个更多的手/具体的答案。问候编辑修复意外代码。(与实际错误无关)
3 回答
![?](http://img1.sycdn.imooc.com/54584f8f00019fc002200220-100-100.jpg)
胡子哥哥
TA贡献1825条经验 获得超6个赞
#!/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!"
ls
添加回答
举报
0/150
提交
取消