【问题标题】:kill process with python用python杀死进程
【发布时间】:2010-11-18 12:35:19
【问题描述】:

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

1) 进程名称(在 linux 上)。

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

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

提前感谢您的帮助。

【问题讨论】:

  • 进程名称在 linux 上不是唯一的。如果有多个同名进程怎么办?另外,系统如何知道如何重新启动进程?您似乎在复制 logrotate 功能....
  • 你如何确定被杀死的进程实际上正在写入该日志文件?假设用户不会犯错听起来很危险。这些错误是否会造成严重的不良情况?
  • 虽然子进程确实如此,但对于非常简单的命令,用户不需要使用 os.system 的子进程的任何额外复杂性,实际上更容易编码和理解。对于我的工作,我使用 os.system 没有任何问题。

标签: python linux process kill


【解决方案1】:

您可以使用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("<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.

希望对你有帮助

【讨论】:

    【解决方案2】:

    如果您知道如何在终端中执行此操作,则可以使用以下内容:

    import os
    os.system("your_command_here; second_command; third; etc")
    

    这样你最终在 python 中就有了一个迷你 shell 脚本。我也会考虑让这个 shell 脚本独立存在,然后从 python 调用它:

    import os
    os.system("path/to/my_script.sh")
    

    干杯!

    【讨论】:

    • 我喜欢简洁,还有一件事要添加'os.system'返回退出状态码,这样你就可以检查进程是否成功并通过代码处理错误。
    • 一般来说,不鼓励程序员再使用 os.system,因为 subprocess.Popen 提供了更多的选项和支持。特别是,它更好地处理命令行参数并允许管道输出。
    • 谢谢詹姆斯,我会切换到子进程:)
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多