python停止函数运行_如何从外部停止Python函数的执行?

一般来说,我认为您希望在单独的线程中运行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之前,您知道停止条件吗?如果是,您可以将其作为参数传递,并检查它是否在内部满足。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值