Ale*_*lex 38 python linux terminal process
我正在尝试在python中编写一些简短的脚本,这将在子进程中启动另一个python代码,如果尚未启动,则终止终端和应用程序(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" ??? 我错过了什么?
Bak*_*riu 92
使用awesome psutil库非常简单:
p = psutil.Process(pid)
p.terminate()  #or p.kill()
如果您不想安装新库,可以使用该os模块:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 
另请参阅os.kill文档.
如果你有兴趣启动命令,   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是属性而不是方法.