python结束任务之后如何关闭,如何使用pid从Python终止进程?

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

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

解决方案

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)

p.terminate() #or p.kill()

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

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.

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 psutil versions cmdline was an attribute instead of a method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值