首页 > 解决方案 > 如何捕获 pyistaller.__main__.run 的输出

问题描述

我到了一个地步,我只想制作一个外部程序来从 Pyhton 文件中制作 .exe PyInstaller.__main__.run,只需选择几个文件并勾选一些框。但我仍然想看看流程的输出。而且由于它们在 Python-IDEs shell 中显示为红色,我认为它们是(裁剪为一行)错误输出,所以我尝试覆盖sys.stderr但根本没有成功。但由于它们既不是标准输出,sys.stdout我不知道如何获得它们。所以我想到了两种可能的方法来解决这个问题,但不知道如何做每一个,也没有在我的谷歌研究中找到任何东西:

a)这里有人知道如何获得这些输出的解决方案(赞赏)

或者

b)我需要一个选项来控制 shell 输出窗口是否在后台或前台(或图标化/去图标化)。

提前致谢。

标签: python-3.xoutputpyinstaller

解决方案


因此,由于似乎没有人有答案,我想发布我发现的解决方案:

import subprocess
from tkinter import *
from threading import Thread

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.rowconfigure(0,weight=1)
        self.columnconfigure(0,weight=1)
        self.text=Text(self)
        self.text.grid(row=0,column=0,sticky=NSEW)
        sby=Scrollbar(self,command=self.text.yview)
        sby.grid(row=0,column=1,sticky=NS)
        sbx=Scrollbar(self,command=self.text.xview,orient=HORIZONTAL)
        sbx.grid(row=1,column=0,sticky=EW)
        self.text.config(yscrollcommand=sby.set,xscrollcommand=sbx.set)
        Button(self,text='Start',command=self.callback).grid(row=2,column=0,columnspan=2,pady=5)
        #creating a tkinter window with text widget to display the outputstream and start up button

        self.thread=Thread(target=self.update_)
        self.thread.deamon=True
        #creating Thread

        self.mainloop()
    def callback(self):
        sui=subprocess.STARTUPINFO()
        sui.dwFlags|=subprocess.STARTF_USESHOWWINDOW
        #setting subprocess startupflags so that ther won't be an extra shell prompt
        self.prc=subprocess.Popen(('~/Python/Scripts/pyinstaller.exe', ... , '~/myprg.py'),
                                  stdout=subprocess.PIPE,stderr=subprocess.PIPE,startupinfo=sui)
        #starting subprocess with redirected stdout and stderr
        self.thread.start()
    def update_(self):
        try:
            with self.prc.stderr as pipe:
                for line in iter(pipe.readline,b''): self.text.insert(END,line)
                #inserting stderr output stream as is comes
        finally: pass

if __name__=='__main__':
    App()

推荐阅读