有什么方法可以使用 subprocess.call()
或 subprocess.Popen()
并通过 Tkinter 的 Entry
小部件与标准输入交互, 并将标准输出输出到 Text
小部件?
我不太确定如何处理这样的事情,因为我是使用 subprocess
模块的新手。
最佳答案
我认为我已经掌握了使用 Entry
作为子进程的标准输入的基础知识。您可能需要根据自己的需要调整它(重新:输出到 Text
小部件)。
这个例子调用了一个测试脚本:
# test.py:
#!/usr/bin/env python
a = raw_input('Type something!: \n') #the '\n' flushes the prompt
print a
这只需要一些输入(来自 sys.stdin
)并打印出来。
通过 GUI 调用它并与之交互是通过以下方式完成的:
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有关子进程问题标准输出的想法。您需要编写一个新的标准输出以将标准输出重定向到文本小部件,例如:
class MyStdout(object):
def __init__(self,textwidget):
self.textwidget = textwidget
def write(self,txt):
self.textwidget.insert(END,txt)
sys.stdout = MyStdout(mytextwidget)
但我建议阅读人们已经实现这一目标的其他示例。
关于python - subprocess.call() 与 GUI (Tkinter) 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10890076/