【发布时间】:2019-02-11 14:15:33
【问题描述】:
我想编写一个 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,并且支持使用相同的proc_def命令启动的多个进程。
【问题讨论】:
-
您最好使用其他一些模块来实现此目的,例如
psutil或类似的:)。这是链接psutil.readthedocs.io/en/latest -
所以我优化了我的脚本,用
if psutil.pid_exists(int(key)):和else替换了第二个try/except循环。完美运行。感谢您的提示。
标签: python linux subprocess