python - Tkinter 为子进程(子进程)提供输入
问题描述
我目前正在开发一个与另一个外部程序并行运行的 GUI 程序。
所以我使用了子进程,你可以在下面的代码中看到。
此外,我尝试启用 GUI 程序和外部程序之间的通信
所以我使用了线程和队列。
到目前为止,我认为我成功地建立了 GUI 程序和外部程序之间的连接。但是,我不知道如何将命令行输入提供给外部程序,以及如何从外部程序获取输出
这是我制作的代码。我尝试使用 subprocess.stdin.write() 进行命令行输入,但是,不知何故,这似乎没有发生任何事情。
任何想法将不胜感激
def read_pipe(process, widget, queue):
interval = 1
if not queue.empty():
line = queue.get()
widget.insert(1.0, line)
print(line)
else:
interval = 5
widget.after(interval, lambda: read_pipe(process, widget, queue))
def queue_in(process, command, queue):
for line in iter(command.readline, b''):
process.stdin.write(str(line) + "\n")
tid = threading.Thread(target = queue_line, args=(process.stdout, q))
tid.daemon = True
tid.start()
def queue_line(pipe, queue):
for line in iter(pipe.readline, b''):
queue.put(line)
def main_window():
root = Tk()
root.title("Seoul Cell")
root.geometry("1100x900")
root.resizable(True, True)
global monitor1
monitor1 = Layout(root)
monitor1.pack(fill="both", expand=True)
# Script
script_frame = LabelFrame(root, text = "script")
script_frame.pack(fill='x', side="bottom",padx=10, pady=10)
script_menu_frame = Frame(script_frame)
script_menu_frame.pack(fill='x')
queue_prog = queue.Queue()
# Script Text box
def queue_put(event):
command = bytearray(terminal_entry.get().encode())
command = io.BytesIO(command)
terminal_entry.delete(0, END)
tid = threading.Thread(target=queue_in, args=(process_exe, command, q))
tid.start()
def subprocess1(program):
process_exe = subprocess.Popen(program, stdout= subprocess.PIPE,
stdin=subprocess.PIPE, universal_newlines=True)
return process_exe
scrollbar_script = Scrollbar(script_frame)
scrollbar_script.pack(side='right',fill="y")
terminal_entry = Entry(script_frame)
terminal_entry.bind('<Return>', queue_put)
terminal_entry.pack(fill='x', padx=3, pady=20)
global script
script = Text(script_frame, height=10, yscrollcommand=scrollbar_script.set)
script.pack(fill='x', side="bottom", padx=5, pady=5)
scrollbar_script.config(command=script.yview)
program = filedialog.askopenfilename(title = 'Choose the execution File')
thread2 = threading.Thread(target= lambda q, arg1: q.put(subprocess1(arg1)), args= (queue_prog, program))
thread2.daemon = True
thread2.start()
process_exe = queue_prog.get()
tid = threading.Thread(target = queue_line, args=(process_exe.stdout, q))
tid.daemon = True
tid.start()
root.after(0, lambda: read_pipe(process_exe, script, q))
root.mainloop()
if __name__ == '__main__':
q = queue.Queue()
main_window()
解决方案
推荐阅读
- python - 无法将焦点重新回到主窗口并单击断开连接按钮
- excel - 复制并粘贴符合条件的所有单元格
- javascript - 使用文本链接打开 tawk.to 的小部件聊天时出现问题..有人可以帮我吗?
- java - 在 Java (apache poi) 中将文件另存为 CSV
- css - CSS给出错误:“样式规则的预期选择器”
- repast-simphony - Repast:从负刻度开始模拟
- c - FreeRTOS 中 strnlen 的隐式声明
- javascript - Javascript - 如何等待异步函数完成然后执行另一个函数?
- r - 在 R 中,如何构建一个包含一些引用列表中较早元素的元素的列表?
- ruby-on-rails - 如何遍历“application/ld+json”中的记录