首页 > 解决方案 > 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()

标签: pythonmultithreadingtkintersubprocess

解决方案


推荐阅读