Redirecting stdout to tkinter immediately (without waiting for the process to complete)

后端 未结 1 463
陌清茗
陌清茗 2021-01-27 06:51

I am writing a python app to take some inputs from the user and call a shell script based on these inputs.

This shell script can run for quite sometime, and I want to re

相关标签:
1条回答
  • 2021-01-27 07:45

    As p.communicate() will wait for the process to complete, so use p.poll() and p.stdout.readline() instead. Also put the process in a thread to avoid blocking the main thread:

    import threading
    ...
    class Gui(GuiApp):
        ...
        def runScript(self):
            print('started')
            p = subprocess.Popen(['./shellScript.sh'], stdout=subprocess.PIPE, bufsize=1, text=True)
            while p.poll() is None: # check whether process is still running
                msg = p.stdout.readline().strip() # read a line from the process output
                if msg:
                    print(msg)
            print('finished')
    
        def testRun(self, event=None):
            # create a thread to run the script
            threading.Thread(target=self.runScript, daemon=True).start()
    
    0 讨论(0)
提交回复
热议问题