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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17856928/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:22:16  来源:igfitidea点击:

How to terminate process from Python using pid?

pythonlinuxprocessterminal

提问by Alex

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).

我正在尝试在 python 中编写一些简短的脚本,如果尚未启动,它将在子进程中启动另一个 python 代码,否则终止终端和应用程序(Linux)。

So it looks like:

所以它看起来像:

#!/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 )

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 datis not equal to "x"??? What I've missed ?

存在缺乏通过应用程序从文件“.proc”读取的 pid 命名进程的知识的问题。另一个问题是解释器说名为dat 的字符串不等于"x"??? 我错过了什么?

采纳答案by Bakuriu

Using the awesome psutillibrary it's pretty simple:

使用很棒的psutil库非常简单:

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

If you don't want to install a new library, you can use the osmodule:

如果您不想安装新库,可以使用该os模块:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.killdocumentation.

另请参阅os.kill文档



If you are interested in starting the command python StripCore.pyif it is not running, and killing it otherwise, you can use psutilto do this reliably.

如果您有兴趣在命令python StripCore.py未运行时启动该命令, 否则将其终止,您可以使用它psutil来可靠地执行此操作。

Something like:

就像是:

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'])

Sample run:

示例运行:

$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.


Note: In previous psutilversions cmdlinewas an attributeinstead of a method.

注意:在以前的psutil版本中cmdline是一个属性而不是一个方法。

回答by suprjami

I wanted to do the same thing as, but I wanted to do it in the one file.

我想做同样的事情,但我想在一个文件中做。

So the logic would be:

所以逻辑是:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff
  • 如果有我名字的脚本正在运行,杀死它,然后退出
  • 如果我的名字的脚本没有运行,做一些事情

I modified the answer by Bakuriu and came up with this:

我修改了 Bakuriu 的答案并想出了这个:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

运行脚本将执行脚本执行的任何操作。运行该脚本的另一个实例将终止该脚本的任何现有实例。

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

我用它来显示一个小的 PyGTK 日历小部件,它在我点击时钟时运行。如果我单击并且日历未启动,则会显示日历。如果日历正在运行并且我单击时钟,日历就会消失。