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

我想在Python中写一些简短的脚本,如果不是已经开始,terminal和应用程序(Linux)将启动另一个子程序中的Python代码。

所以它看起来像:

#!/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的string不等于“x” ? 我错过了什么?

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

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

如果你不想安装一个新的库,你可以使用os模块:

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

如果你有兴趣启动python StripCore.py命令,如果它没有运行,并杀死它,否则,你可以使用psutil做到这一点可靠。

就像是:

 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是一个属性而不是一个方法。

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

所以逻辑是:

  • 如果一个脚本与我的名字正在运行,杀死它,然后退出
  • 如果我的名字脚本没有运行,请做些东西

我修改了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... 

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

我用这个来显示一个点击时钟的时候运行的小PyGTK日历小部件。 如果我点击并且日历不在,日历显示。 如果日历正在运行,我点击时钟,日历就会消失。