一般来说,我认为您希望在单独的线程中运行long_running_function,并让它偶尔向主线程报告其信息。
This post在wxpython程序中给出了一个类似的例子。
假设您是在wxpython之外执行此操作,那么应该可以用threading.Thread和PubSub替换wx.CallAfter和wx.Publisher。
它看起来像这样:import threading
import time
def myfunction():
# subscribe to the long_running_function
while True:
# subscribe to the long_running_function and get the published data
if condition_met:
# publish a stop command
break
time.sleep(1)
def long_running_function():
for loop in loops:
# subscribe to main thread and check for stop command, if so, break
# do an iteration
# publish some data
threading.Thread(group=None, target=long_running_function, args=()) # launches your long_running_function but doesn't block flow
myfunction()
我已经很久没用过pubsub了,所以我不能很快地编写代码,但它应该能让你达到目的。
另外,在启动long_running_function之前,您知道停止条件吗?如果是,您可以将其作为参数传递,并检查它是否在内部满足。