有沒有辦法使用subprocess.call()
或subprocess.Popen()
並通過的Tkinter的Entry
插件的標準輸入和輸出交互的標準輸出到Text
小部件?subprocess.call()與GUI(Tkinter的)交互
我不太確定如何處理這樣的事情,因爲我是使用subprocess
模塊的新手。
有沒有辦法使用subprocess.call()
或subprocess.Popen()
並通過的Tkinter的Entry
插件的標準輸入和輸出交互的標準輸出到Text
小部件?subprocess.call()與GUI(Tkinter的)交互
我不太確定如何處理這樣的事情,因爲我是使用subprocess
模塊的新手。
認爲我已經有了使用Entry
作爲標準輸入到子進程的基礎知識。您可能需要根據自己的需要來調整它(重新輸出到Text
小部件)。
此示例調用一個測試腳本:
# test.py:
#!/usr/bin/env python
a = raw_input('Type something!: \n') #the '\n' flushes the prompt
print a
,僅僅需要一些輸入(從sys.stdin
)並打印。
調用此並通過圖形用戶界面與它交互與完成:
from Tkinter import *
import subprocess
root = Tk()
e = Entry(root)
e.grid()
b = Button(root,text='QUIT',command=root.quit)
b.grid()
def entryreturn(event):
proc.stdin.write(e.get()+'\n') # the '\n' is important to flush stdin
e.delete(0,END)
# when you press Return in Entry, use this as stdin
# and remove it
e.bind("<Return>", entryreturn)
proc = subprocess.Popen('./test.py',stdin=subprocess.PIPE)
root.mainloop()
現在無論是鍵入Entry
e
(其次爲Return
鍵),然後通過標準輸入傳遞給proc
。
希望這會有所幫助。
另請參閱this瞭解有關子流程問題stdout的想法。你需要寫一個新的標準輸出到標準輸出重定向到textwidget,是這樣的:
class MyStdout(object):
def __init__(self,textwidget):
self.textwidget = textwidget
def write(self,txt):
self.textwidget.insert(END,txt)
sys.stdout = MyStdout(mytextwidget)
,但我會建議你閱讀,人們已經實現了這個其他的例子。
用Python對象替換'sys.stdout'不會影響'subprocess''stdout,請參見[這個答案](http://stackoverflow.com/a/22434262/4279)。要在GUI小部件中顯示子進程的stdout,請參閱[本答案](http://stackoverflow.com/a/32682520/4279) – jfs
哇哈哈,第一次我的一個問題就連一天都沒有發表評論; P –
有很多SO和其他地方的答案(例如http://stackoverflow.com/questions/665566/python-tkinter -shell-to-gui)將stdout重定向到Tkinter小部件。但是,我也想知道如何將stdin從GUI小部件傳遞給子進程,如果有人碰巧知道! – Jdog
是的,我想知道如何讓STDIN工作(這將是awsome!xD),但是鏈接:) –