Python file real time output in windows CMD/PowerShell

Viewed 37

I have two .py file, as:

A.py, a GUI by tkinter
B.py, target app python file

I'd like to run B.py by using subprocess.Popen() method in A.py, and get the log of B.py by stdout approach, then put the log information into GUI of A.py in real time.

I have already implemented this and successed running in Pycharm.

But my quesion is when using windows CMD or Powershell to run a.py by key in 'python a.py' (for some guy do not have pycharm to use). Then the log info can only be put into GUI after whole B.py procedure done, not timely.

Is there any solution? appreciate for your suggestion!

Code as below:

'''
import os
import queue
import subprocess
import sys
import tkinter as tk
import time
import threading

log_queue = queue.Queue()


def my_run():
    sub_proc = subprocess.Popen('python b.py', shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.getcwd())

    for data in iter(sub_proc.stdout.readline, b''):
        if not data:
            break
        else:
            log = data.decode(sys.getdefaultencoding())
            log_queue.put(log)


def my_thread(func):
    t = threading.Thread(target=func)
    t.Daemon = True
    t.start()


def my_log():
    while not log_queue.empty():
        log = log_queue.get()
        text.insert(tk.END, "Whaaat:%s \t-- %s\n" % (log, time.ctime()))

    root.after(100, my_log)


root = tk.Tk()
text = tk.Text(root)
text.pack()
tk.Button(root, text='RUN!', command=lambda: my_thread(my_run)).pack()
root.after(100, my_log)
root.mainloop()

'''
0 Answers
Related