用python杀死进程 [英] kill process with python

查看:617
本文介绍了用python杀死进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个从用户获得以下内容的脚本:

I need to make a script that gets from the user the following:

1)进程名称(在Linux上).

1) Process name (on linux).

2)此进程写入的日志文件名.

2) The log file name that this process write to it.

它需要终止该进程并确认该进程已关闭. 将日志文件名更改为带有时间和日期的新文件名. 然后再次运行该过程,确认它已启动,以便继续写入日志文件.

It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then run the process again, verify that it's up in order it will continue to write to the log file.

预先感谢您的帮助.

推荐答案

您可以使用pgrep命令像这样检索具有其名称的进程ID(PID):

You can retrieve the process id (PID) given it name using pgrep command like this:

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("<command to run the process>") 
# 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.

希望这可以帮助

这篇关于用python杀死进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆