栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用pid从Python终止进程?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用pid从Python终止进程?

使用很棒的

psutil
库非常简单:

p = psutil.Process(pid)p.terminate()  #or p.kill()

如果您不想安装新的库,可以使用以下

os
模块:

import osimport signalos.kill(pid, signal.SIGTERM) #or signal.SIGKILL

另请参阅

os.kill
文档。


如果您有兴趣在命令

python StripCore.py
未运行时启动 它,否则将其杀死,则可以
psutil
可靠地使用它。

就像是:

import psutilfrom subprocess import Popenfor process in psutil.process_iter():    if process.cmdline() == ['python', 'StripCore.py']:        print('Process found. Terminating it.')        process.terminate()        breakelse:    print('Process not found: starting it.')    Popen(['python', 'StripCore.py'])

样品运行:

$python test_strip.py   #test_strip.py contains the pre aboveProcess not found: starting it.$python test_strip.py Process found. Terminating it.$python test_strip.py Process not found: starting it.$killall python$python test_strip.py Process not found: starting it.$python test_strip.py Process found. Terminating it.$python test_strip.py Process not found: starting it.

注意 :在以前的

psutil
版本中,
cmdline
属性 而不是方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号