Python脚本检查特定Linux命令是否仍在运行

2024-04-18 12:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个Python脚本,它每分钟都会检查一些预定义的进程是否仍在Linux机器上运行,以及是否在崩溃时没有打印时间戳。我已经写了一个脚本,正是这样做,但不幸的是,它只与一个进程正常工作。你知道吗

这是我的密码:

import subprocess
import shlex
import time
from datetime import datetime

proc_def = "top"
grep_cmd = "pgrep -a " + proc_def
try:
    proc_run = subprocess.check_output(shlex.split(grep_cmd)).decode('utf-8')
    proc_run = proc_run.strip().split('\n')
    '''
    Creating a dictionary with key the PID of the process and value
    the command line
    '''
    proc_dict = dict(zip([i.split(' ', 1)[0] for i in proc_run],
                         [i.split(' ', 1)[1] for i in proc_run]))

    check_run = "ps -o pid= -p "

    for key, value in proc_dict.items():
        check_run_cmd = check_run + key
        try:
            # While the output of check_run_cmd isn't empty line do
            while subprocess.check_output(
                                          shlex.split(check_run_cmd)
                                          ).decode('utf-8').strip():
                # This print statement is for debugging purposes only
                print("Running")
                time.sleep(3)
        '''
        If the check_run_cmd is returning an error, it shows us the time
        and date of the crash as well as the PID and the command line
        '''
        except subprocess.CalledProcessError as e:
            print(f"PID: {key} of command: \"{value}\" stopped
                  at {datetime.now().strftime('%d-%m-%Y %T')}")
            exit(1)
# Check if the proc_def is actually running on the machine
except subprocess.CalledProcessError as e:
    print(f"The \"{proc_def}\" command isn't running on this machine")

例如,如果有两个top进程,它将只显示其中一个进程的崩溃时间信息,并且它将退出。只要有另一个进程在运行,我就想保持活动状态,只有在两个进程都被终止时才退出。它应该在每个进程崩溃时提供信息。你知道吗

它也不应仅限于两个进程,并且支持以同一proc_def命令启动的多个进程。你知道吗


Tags: ofthekeyrunimportcmdfor进程
1条回答
网友
1楼 · 发布于 2024-04-18 12:42:14

必须稍微改变一下逻辑,但基本上你想要一个无限循环,交替检查所有进程,而不是反复检查同一个进程:

import subprocess
import shlex
import time
from datetime import datetime

proc_def = "top"
grep_cmd = "pgrep -a " + proc_def
try:
    proc_run = subprocess.check_output(shlex.split(grep_cmd)).decode('utf-8')
    proc_run = proc_run.strip().split('\n')
    '''
    Creating a dictionary with key the PID of the process and value
    the command line
    '''
    proc_dict = dict(zip([i.split(' ', 1)[0] for i in proc_run],
                         [i.split(' ', 1)[1] for i in proc_run]))

    check_run = "ps -o pid= -p "
    while proc_dict:
        for key, value in proc_dict.items():
            check_run_cmd = check_run + key
            try:
                # While the output of check_run_cmd isn't empty line do
                subprocess.check_output(shlex.split(check_run_cmd)).decode('utf-8').strip()
                # This print statement is for debugging purposes only
                print("Running")
                time.sleep(3)
            except subprocess.CalledProcessError as e:
                print(f"PID: {key} of command: \"{value}\" stopped at {datetime.now().strftime('%d-%m-%Y %T')}")
                del proc_dict[key]
                break
# Check if the proc_def is actually running on the machine
except subprocess.CalledProcessError as e:
    print(f"The \"{proc_def}\" command isn't running on this machine")

这与原始代码中的问题相同,即时间分辨率为3秒,如果在此脚本期间运行新进程,则不会ping它(尽管这可能是需要的)。你知道吗

第一个问题可以通过减少睡眠时间来解决,具体取决于您需要什么;第二个问题可以通过运行初始行来解决,在while True中创建proc_dict。你知道吗

相关问题 更多 >