2011-04-05 79 views
2

我試圖從同一個Python腳本輸出不同的信息(很像this fellow)。我的研究似乎指出的方法是使用subprocess.Popen和運行cat在窗口中顯示終端的stdin來打開一個新的xterm窗口。然後我會寫像這樣必要的信息,以子進程的標準輸入:使用Python的子進程在新的Xterm窗口中顯示輸出

from subprocess import Popen, PIPE 

terminal = Popen(['xterm', '-e', 'cat'], stdin=PIPE) #Or cat > /dev/null 
terminal.stdin.write("Information".encode()) 

字符串「信息」,那麼將在新的xterm顯示。然而,這種情況並非如此。 xterm不顯示任何內容,stdin.write方法只是返回字符串的長度,然後繼續。我不確定是否存在對子流程和管道工作方式的誤解,但如果有人能夠幫助我,我將非常感激。謝謝。

回答

1

這不起作用,因爲你管的東西到xterm本身不是xterm裏面運行的程序。考慮使用命名管道:

import os 
from subprocess import Popen, PIPE 
import time 

PIPE_PATH = "/tmp/my_pipe" 

if not os.path.exists(PIPE_PATH): 
    os.mkfifo(PIPE_PATH) 

Popen(['xterm', '-e', 'tail -f %s' % PIPE_PATH]) 


for _ in range(5): 
    with open(PIPE_PATH, "w") as p: 
     p.write("Hello world!\n") 
     time.sleep(1) 
+0

非常感謝。有一件事是,當在腳本中關閉管道之前用於更新終端時,我必須將其設置爲p = open(PIPE_PATH,'w',1)。 – 2011-04-05 22:10:52

+0

如何使用'gnome-terminal'而不是'xterm'? – shiva 2016-07-15 07:09:50

+0

@shiva我編輯了一下答案。通過上面的代碼片段,您可以用Popen行中的gnome-terminal替換xterm。 – 2016-07-15 08:15:05

相關問題