How terminate Python thread without checking flag continuously(如何在不连续检查标志的情况下终止 Python 线程)
问题描述
class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
cmd = [ "bash", 'process.sh']
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
print ("-- " + line.rstrip())
print "Exiting " + self.name
def stop(self):
print "Trying to stop thread "
self.run = False
thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()
所以我有上面显示的线程,实际上在 windows 上工作,process.sh 是在 cygwin 中运行的 bash 脚本,大约需要 5 分钟才能完成执行,所以它不是一个循环,它是一些模拟过程
So i have thread like show above, actually work on windows and process.sh is bash script which run in cygwin and takes around 5 min to finish execution so its not a loop its some simulation proecess
我想在这个类中创建 stop() 函数,以便我可以在需要时立即终止脚本.终止后,我不希望 process.sh 脚本有任何有用的结果
i want to create stop() function in this class so that i can terminate script immediately when i want. after termination i am not expecting any useful result from process.sh script
请你建议任何方法,如果可能的话也请给出一点解释..
please can u suggest any method, If possible please give little explanation too..
推荐答案
对于您的特定示例,通过使用 Popen
对象的 terminate()
方法...
For your particular example, it's probably easiest to terminate the thread by terminating the subprocess it spawns using the Popen
object's terminate()
method...
class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.process = None
def run(self):
print "Starting " + self.name
cmd = [ "bash", 'process.sh']
self.process = p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
print ("-- " + line.rstrip())
print "Exiting " + self.name
def stop(self):
print "Trying to stop thread "
if self.process is not None:
self.process.terminate()
self.process = None
thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()
...导致 SIGTERM
被发送到 bash
,并且下一次调用 p.stdout.readline()
以引发一个异常,将终止线程.
...causing a SIGTERM
to be sent to bash
, and the next call to p.stdout.readline()
to raise an exception, which will terminate the thread.
这篇关于如何在不连续检查标志的情况下终止 Python 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不连续检查标志的情况下终止 Python 线程
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01