如何在不连续检查标志的情况下终止 Python 线程

How terminate Python thread without checking flag continuously(如何在不连续检查标志的情况下终止 Python 线程)

本文介绍了如何在不连续检查标志的情况下终止 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 线程

基础教程推荐