gpt4 book ai didi

python - 执行 python 脚本并在 WXPython GUI 中显示进度

转载 作者:行者123 更新时间:2023-12-01 08:11:21 30 4
gpt4 key购买 nike

我们如何在 WXPython GUI 中运行 python 脚本并显示日志。我已经尝试过,但它没有运行它,而是打开一个 cmd 并在那里运行。以前我只是从命令行运行 Python 脚本,它完成了他的工作,但新的要求不是打开命令提示符,而是应该打开 GUI 并执行主要的 python 脚本。我也是 python 新手(使用 python 进行操作以使其独立于平台的原因)。

`
import wx, os, logging, sys, subprocess

logger = logging.getLogger(__name__)

class WxTextCtrlHandler(logging.Handler):

def __init__(self, ctrl):
logging.Handler.__init__(self)
self.ctrl = ctrl

def emit(self, record):
s = self.format(record) + '\n'
wx.CallAfter(self.ctrl.WriteText, s)`


class WindowClass(wx.Frame):

def __init__(self):
TITLE = "wxPython Logging To A Control"
wx.Frame.__init__(self, None, wx.ID_ANY, TITLE)
panel = wx.Panel(self, wx.ID_ANY)
log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,200), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
py = os.path.join(os.getcwd(), 'test1.py')
log = subprocess.call([sys.executable, py])
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(log, 1, wx.ALL|wx.EXPAND, 5)
panel.SetSizer(sizer)
handler = WxTextCtrlHandler(log)
logger.addHandler(handler)
#self.Centre
FORMAT = "%(asctime)s %(levelname)s %(message)s"
handler.setFormatter(logging.Formatter(FORMAT))
logger.log(1,"More? click again!")
label = wx.StaticText(panel, label = "Hello World", pos = (100,50))
self.Show()

app = wx.App(False)
WindowClass()
app.MainLoop()`

最佳答案

我从未使用过日志记录,但我想您想要如下所示的内容:
您需要使用 subprocess.Popen 而不是 subprocess.call,然后poll 结果。
如果 Gui 要保持“事件”状态,您还需要调用 Yield,因为您将处于循环中,因此 wx MainLoop 将被有效卡住。

主程序

import wx
import subprocess
from signal import SIGKILL
import os

class MyFrame(wx.Frame):

def __init__(self, parent, id=-1, title='External program test',
pos=wx.DefaultPosition, size=(600, 600)):
wx.Frame.__init__(self, parent, id, title, pos, size)
self.text1 = wx.TextCtrl(self, -1, '', wx.DefaultPosition, wx.Size(500,500),
wx.NO_BORDER | wx.TE_MULTILINE)
stop_button = wx.Button(self, wx.ID_ANY, "&Stop", pos=(400,520))
self.Bind(wx.EVT_BUTTON, self.OnStop)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Show()
#Call python with -u for unbuffer I/O
p = subprocess.Popen(["python", "-u", "testp.py"], stdout=subprocess.PIPE, bufsize=-1)
self.pid = p.pid
#Poll process for output
while p.poll() is None:
x = p.stdout.readline().decode() #decode bytes but don't strip linefeeds
self.text1.write(x)
wx.GetApp().Yield() # Yield to MainLoop for interactive Gui
self.text1.write("\nProcess has ended")

def OnStop(self, event):
try:
os.kill(int(self.pid), SIGKILL)
self.text1.write("\nProcess killed")
except:
self.text1.write("\nProcess has ended")

def OnClose(self, event):
self.Destroy()

if __name__ == '__main__':
app = wx.App()
frame = MyFrame(None)
app.MainLoop()

调用的程序

import time
counter = 0
while counter < 40:
print ("Counter:",counter)
counter += 1
time.sleep(0.5)

结果 enter image description here

关于python - 执行 python 脚本并在 WXPython GUI 中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234427/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com