gpt4 book ai didi

python - 如果没有从主模块调用 wx.app.mainloop,线程将无法启动

转载 作者:行者123 更新时间:2023-11-28 16:29:30 25 4
gpt4 key购买 nike

我希望有人能向我解释这种行为。如果我导入一个启动 wxpython 接口(interface)的模块,线程在 app.MainLoop() 结束之前无法启动。最简单的例子:

simple_app.py

import wx
from threading import Thread

def test():
from time import sleep
while 1:
print("thread still running")
sleep(2)

app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
thread = Thread(target=test)
thread.setDaemon(True)
thread.start()
app.MainLoop()

主要.py

import simple_app

如果你单独运行 simple_app.py 它工作正常,如果你运行 main.py 线程永远不会启动......为什么?我感觉这与线程无法获得锁有关。

最佳答案

simple_app.py 中的第二个线程正在尝试导入 time 模块,而导入已经在运行,这会导致 simple_app 正在从主模块导入。因为导入在导入模块时获取当前线程的解释器导入锁。已经documented .

主模块中的线程可以导入其他模块,这就是将 simple_app.py 作为主模块运行的原因。将 from time import sleep 移动到 simple_app.py 中的模块级别解决了这个问题。

运行以下代码有助于更好地理解问题;

我的时间.py
从时间导休眠眠

简单的应用程序.py

import imp
import sys
from threading import Thread
from time import sleep

import wx

class MyFinder(object):
def __init__(self):
print('MyFinder initializing')
if imp.lock_held():
while imp.lock_held():
print('import lock held')
sleep(2)
print('import lock released')
else:
print('import lock is not held')

def find_module(self, module, package=None):
print('MyFinder.find_module called with module name "{}", pakcage name "{}"'.format(module, package))
return None


def test():
sys.meta_path.append(MyFinder())
from my_time import sleep
count = 0
while True:
print("{} thread still running".format(count))
count += 1
sleep(2)


app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
thread = Thread(target=test)
thread.setDaemon(True)
thread.start()
app.MainLoop()

关于python - 如果没有从主模块调用 wx.app.mainloop,线程将无法启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427280/

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