python怎么杀死进程_用python杀死进程

小编典典

您可以使用以下pgrep命令检索给定名称的进程ID(PID):

import subprocess

import signal

import os

from datetime import datetime as dt

process_name = sys.argv[1]

log_file_name = sys.argv[2]

proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)

# Kill process.

for pid in proc.stdout:

os.kill(int(pid), signal.SIGTERM)

# Check if the process that we killed is alive.

try:

os.kill(int(pid), 0)

raise Exception("""wasn't able to kill the process

HINT:use signal.SIGKILL or signal.SIGABORT""")

except OSError as ex:

continue

# Save old logging file and create a new one.

os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))

# Empty the logging file.

with open(log_file_name, "w") as f:

pass

# Run the process again.

os.sytsem("")

# you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.

# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again.

希望这可以帮助

2020-06-02

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值