Python PIPE to popen stdin

前端 未结 3 1981
南方客
南方客 2021-01-14 03:57

I am attempting something very similar to real time subprocess.Popen via stdout and PIPE

I, however, want to send input to the running process as well.

If I

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 04:20

    A simple portable solution in your case with minimal code changes might be to create a writer thread that get items from a queue and writes them to the process' stdin and then put values into the queue whenever the button is pressed:

    from subprocess import Popen, PIPE, STDOUT
    from Queue import Queue
    
    class Example(Frame):
        def __init__(self, parent, queue):
           # ...
           self.queue = queue
        # ...
        def send(self): # should be call on the button press
            self.queue.put(prompt.get())
    
    def writer(input_queue, output): 
        for item in iter(input_queue.get, None): # get items until None found
            output.write(item)
        output.close()
    
    def MyThread(queue):
        # ...
        #NOTE: you must set `stdin=PIPE` if you wan't to write to process.stdin
        process = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        Thread(target=writer, args=[queue, process.stdin]).start()
        # ...
    
    def main():
        # ...
        queue = Queue()
        app = Example(root, queue)
        Thread(target=MyThread, args=[queue]).start()
        # ...
        root.mainloop()
        queue.put(None) # no more input for the subprocess
    

提交回复
热议问题