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

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

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线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆