如何使用pid从Python终止进程? [英] How to terminate process from Python using pid?
问题描述
我正在尝试在python中编写一些简短的脚本,如果尚未启动该脚本,则会在子进程中启动另一个python代码,否则终止终端&应用(Linux).
I'm trying to write some short script in python which would start another python code in subprocess if is not already started else terminate terminal & app (Linux).
它看起来像:
#!/usr/bin/python
from subprocess import Popen
text_file = open(".proc", "rb")
dat = text_file.read()
text_file.close()
def do(dat):
text_file = open(".proc", "w")
p = None
if dat == "x" :
p = Popen('python StripCore.py', shell=True)
text_file.write( str( p.pid ) )
else :
text_file.write( "x" )
p = # Assign process by pid / pid from int( dat )
p.terminate()
text_file.close()
do( dat )
有一个问题,即应用程序从文件.proc" 读取的pid缺乏对过程进行命名的知识. 另一个问题是解释器说名为 dat 的字符串不等于"x" ???我错过了什么?
Have problem of lacking knowledge to name proces by pid which app reads from file ".proc". The other problem is that interpreter says that string named dat is not equal to "x" ??? What I've missed ?
推荐答案
使用超赞的 psutil
库非常简单:
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
如果您不想安装新的库,则可以使用os
模块:
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
另请参见 os.kill
文档.
See also the os.kill
documentation.
如果您有兴趣启动命令python StripCore.py
(如果它未运行),或者将其杀死,则可以使用psutil
可靠地执行此操作.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
类似的东西:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
样品运行:
$python test_strip.py #test_strip.py contains the code above
Process 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
是属性而不是方法.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
这篇关于如何使用pid从Python终止进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!