无法使用Python在Windows上从生成的子进程读取stdout

问题描述 投票:0回答:1

我正在尝试为非常简单的Windows终端应用程序(此处为二进制文件,https://github.com/00-matt/randomx-stress/releases/download/200109/randomx-stress-windows-200109.zip)构建GUI前端,并使用popen将终端应用程序作为子进程启动,并将输出馈入队列,然后读取队列并放入输出到tkinter GUI中。无论我尝试什么,尽管我无法从派生的子进程中从stdout或stderr中获得任何绝对信息。这是我的代码的精简版:

from tkinter import *
import subprocess
import threading
import queue
import os
from os import system
from re import sub
import sys

os.environ["PYTHONUNBUFFERED"] = "1"

def enqueue_output(p, q):
    while True:
        out = p.stdout.readline()
        if out == '' and p.poll() is not None:
            break
        if out:
            print(out.strip(), flush=True)
            q.put_nowait(out.strip())


class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.started = False
        self.p = None
        self.q = queue.Queue()
        self.threads = 1
        self.init_window()

    def init_window(self):
        self.master.title("RandomX Stress Tester")
        self.pack(fill=BOTH, expand=1)

        self.hashrateLabel = Label(self, text="Hashrate: ")
        self.hashrateLabel.after(2000, self.refresh_hashrate)

        self.startButton = Button(self, text="Start", background="green", command=self.startstop)
        self.quitButton = Button(self, text="Quit", command=self.client_exit)

        self.hashrateLabel.place(x=50, y=220)
        self.startButton.place(x=50, y=270)
        self.quitButton.place(x=220, y=270)

    def startstop(self):
        if not self.started:
            self.p = subprocess.Popen([r"randomx-stress.exe", "-t", str(self.threads)],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        shell=True,
                        encoding='utf-8',
                        errors='replace')
            self.t = threading.Thread(target=enqueue_output, args=(self.p, self.q))
            self.t.daemon = True
            self.t.start()
            self.started = True
            self.startButton.config(text="Stop", background="red")
        elif self.started:
            system("taskkill /im randomx-stress.exe /f")
            self.p.kill()
            self.t.join()
            self.started = False
            self.startButton.config(text="Start", background="green")

    def refresh_hashrate(self):
        print("checking hashrate if running")
        if not self.started:
            pass
        elif self.started:
            print("its running")
            try:
                line = self.q.get_nowait()
                print(line)
                if 'H/s' in line:
                    hashrate = line.split(' ')[0]
                    self.hashrateLabel.text = "Hashrate: {0:.2f} h/s".format(hashrate)
            except:
                print("error")
        self.hashrateLabel.after(2000, self.refresh_hashrate)

    def client_exit(self):
        exit()


root = Tk()
root.geometry("400x300")

app = Window(root)
root.mainloop()

我现在怀疑终端应用程序正在缓冲输出,而我无法在Windows上绕过它。如果有人可以确认这是问题所在,并且可能的话提供解决方法,我将不胜感激!

python subprocess stdout
1个回答
1
投票

基于C库的程序,根据stdout的终端(假设用户逐行获取数据)还是管道(为提高效率而使用块缓冲区)来区别对待stdout。在类似Unix的系统上,可以欺骗程序以使其在带有伪tty设备的终端上运行。在Windows上,Microsoft从未实施过等效技术。子进程将阻塞缓冲区。

您可以在写入后通过刷新stdout在被调用程序中解决该问题。这是在C ++中使用endl自动完成的。您的情况是:

std::cout << hashes / difference.count() << " H/s" << endl;
© www.soinside.com 2019 - 2024. All rights reserved.