gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:55 26 4
gpt4 key购买 nike

我想编写一个 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 命令启动多个进程。

最佳答案

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

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 的初始行来解决。

关于检查特定 Linux 命令是否仍在运行的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com