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 回答

胡子哥哥
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
提交
取消