我正在尝试与通过 stdout 和 PIPE 实时运行 subprocess.Popen非常相似的东西。
然而,我也想向正在运行的进程发送输入。
如果我使用单独的线程启动进程,则可以使用
process = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
我可以使用终端发送输入。
如果我想从其他来源发送输入,例如不在线程中的单独函数,该怎么办?
我无法使用Popen.communicate
,因为正在运行的进程永远不会结束,因为我正在尝试与程序进行实时交互。
提前感谢你的帮助。
这是我的完整代码,我希望在点击发送按钮时将输入发送到子进程过程。
from Tkinter import *`
from ttk import *`
import subprocess
from threading import Thread
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Test Client")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
#Label, doesnt change
lbl = Label(self, text="Client:")
lbl.grid(row=0, column=1, sticky=W )
#when output from client is shown
global display
display = Text(self,width=50,height=20)
display.grid(row=1, column=1, sticky=E+W+N+S)
#where user input is taken
global prompt
prompt = Entry(self,width=50)
prompt.grid(row=3, column=1, sticky=E+W+N+S)
#Button that will send input to client
send = Button(self,text="Send",command=self.send)
send.grid(row=3, column=2, sticky=N)
get = Button(self,text="Get",command=self.get)
get.grid(row=2, column=2, sticky=S)
def get(self):
print foo
def send(self):
sent = prompt.get()
def MyThread():
global sent
sent = 2
cmd = ['nc', '-l', '-p', '50000']
process = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
display.insert(INSERT, out)
sys.stdout.write(out)
sys.stdout.flush()
def main():
root = Tk()
root.geometry("500x410+300+300")
app = Example(root)
thread = Thread(target = MyThread, args=())
thread.start()
root.mainloop()
if __name__ == '__main__':
main()
Popen.communicate()
来实现,你试过了吗?当你这样做时会发生什么? - Lie Ryancommunicate
等待子进程完成并读取其所有输出。由于“运行的进程永远不会结束”,这意味着communicate
永远不会返回。因此,他不能使用它。 - abarnertroot.after()
在线程中安排对GUI的调用。避免不必要地使用global
,而可以使用实例变量,例如self.prompt
。你可以使用socket
、select
模块代替运行netcat
。 - jfs