如何在不连续检查标志的情况下终止 Python 线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16262132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How terminate Python thread without checking flag continuously
提问by Ganesh Gore
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()
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
所以我有像上面显示的线程,实际上在 Windows 上工作,而 process.sh 是 bash 脚本,它在 cygwin 中运行,需要大约 5 分钟才能完成执行,所以它不是一个循环,它的一些模拟过程
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
我想在这个类中创建 stop() 函数,以便我可以在需要时立即终止脚本。终止后,我不期望 process.sh 脚本有任何有用的结果
please can u suggest any method, If possible please give little explanation too..
请你建议任何方法,如果可能的话,也请给出一些解释..
采纳答案by Aya
For your particular example, it's probably easiest to terminate the thread by terminating the subprocess it spawns using the Popenobject's terminate()method...
对于您的特定示例,通过使用Popen对象的terminate()方法终止它产生的子进程来终止线程可能是最简单的......
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()
...causing a SIGTERMto be sent to bash, and the next call to p.stdout.readline()to raise an exception, which will terminate the thread.
...导致 aSIGTERM被发送到bash,并且下一次调用p.stdout.readline()以引发异常,这将终止线程。
回答by nacholibre
Python threads are not easy to kill, you can use the multiprocessing module (http://docs.python.org/2/library/multiprocessing.html) which is almost the same and it has terminate() function for killing a processes.
Python 线程不容易被杀死,您可以使用 multiprocessing 模块(http://docs.python.org/2/library/multiprocessing.html),它几乎相同,它具有用于杀死进程的 terminate() 函数。
Here is a little example, taken from the python docs.
这是一个来自 python 文档的小例子。
>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print p, p.is_alive()
<Process(Process-1, initial)> False
>>> p.start()
>>> print p, p.is_alive()
<Process(Process-1, started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print p, p.is_alive()
<Process(Process-1, stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True

