Python子進(jìn)程readline()掛起我試圖完成的任務(wù)是流一個(gè)ruby文件并打印出輸出。(注:我不想一下子把所有的東西都打印出來(lái))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!"問(wèn)題流文件很好。打個(gè)招呼/再見(jiàn)的輸出是用2秒的延遲打印出來(lái)的。正如腳本應(yīng)該工作的那樣。問(wèn)題是readline()掛起,永遠(yuǎn)不會(huì)退出。我從來(lái)沒(méi)有達(dá)到最后的指紋。我知道這里有很多這樣的問(wèn)題,堆積如山,但沒(méi)有一個(gè)問(wèn)題讓我解決了這個(gè)問(wèn)題。我不喜歡整個(gè)子過(guò)程,所以請(qǐng)給我一個(gè)更多的手/具體的答案。問(wèn)候編輯修復(fù)意外代碼。(與實(shí)際錯(cuò)誤無(wú)關(guān))
3 回答

胡子哥哥
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
#!/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
添加回答
舉報(bào)
0/150
提交
取消