python杀死子线程_如何在python中杀死线程中的进程?

该博客探讨了如何使用Python的`subprocess`模块管理和优雅地终止进程,如Tor和Firefox。通过设置定时器,实现了10秒内的优雅退出和20秒后的强制杀死进程。此外,还提到了通过系统调用获取PID并使用不同API来终止进程的方法。
摘要由CSDN通过智能技术生成

您可以使用terminate(优雅)和Popen对象的terminate方法终止创建的进程。像firefox这样的程序往往会立即返回,所以这并不总是有效的。但总的想法是:import subprocess

import threading

def kill_this(procs, hard=False):

"""kill the Popen processes in the list"""

for proc in procs:

if hard:

proc.kill()

else:

proc.terminate()

class A(threading.Thread):

"""Runs tor and firefox, with graceful termination in 10 seconds and

a hard kill in 20 seconds as needed"""

def __init__(self):

Thread.__init__(self)

def run(self):

# create processes

tor = subprocess.Popen(['tor'])

firefox = subprocess.Popen(['firefox'])

# setup timers to kill 'em

soft = threading.Timer(10, kill_this, ((tor, firefox), False))

hard = threading.Timer(20, kill_this, ((tor, firefox), True))

# wait for process exit

tor.wait()

firefox.wait()

soft.cancel()

hard.cancel()

或者,您可以使用系统调用来获取要终止的进程的pid,然后将kill_this转换为使用不同的API:

^{pr2}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值