本文主要是介绍23. python杀死指定进程极其子进程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码
import argparse
import logging
import signal
import threading_c = threading.RLock()
logger = logging.getLogger(name="[ProcessManager]")
logger.setLevel(logging.DEBUG)
# 终端Handler
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('\033[32m %(asctime)s - %(name)s - %(levelname)s - %(message)s \033[0m ')
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)def kill_process(pid, sig=signal.SIGTERM, child_only=False):"""默认: 杀死进程极其子进程:param pid: 待杀死的进程ID:type pid: int:param sig: 杀死进程时使用的信号, 参考 Signal_:type sig: int:param child_only: 是否仅杀死子进程, 而保留该进程:type child_only: bool"""import psutil_c.acquire()try:p = psutil.Process(pid)process_list = p.children(True)try:if not child_only:p.send_signal(sig)logger.info("[Stop] kill father_pid:{pid} success".format(pid=pid))except psutil.NoSuchProcess:passfor sub_process in process_list:try:sub_process.send_signal(sig)logger.info("[Stop] kill child_pid:{pid} success".format(pid=sub_process.pid))except psutil.NoSuchProcess:passfinally:_c.release()if __name__ == '__main__':"""代码执行:python stop.py -p 1234"""parser = argparse.ArgumentParser()parser.add_argument("-p", "--pid", dest="Pid", help="kill进程", type=int)ns = parser.parse_known_args()[0]pid = ns.Pidif pid:kill_process(pid, sig=signal.SIGKILL)logger.info("[Stop] finished")
这篇关于23. python杀死指定进程极其子进程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!