首页 > 解决方案 > 使用 Python 代码获取 Linux 服务信息(性能)

问题描述

我需要使用 Python 代码获取一些服务信息。我想以非常低的 CPU 消耗运行此代码。

这是简化的代码:

import subprocess, time

start_time = time.time()

command1 = "systemctl show alsa-restore.service --property=LoadState,UnitFileState,ActiveState,SubState"
command2 = "systemctl show apt-daily.service --property=LoadState,UnitFileState,ActiveState,SubState"
command3 = "systemctl show cryptdisks-early.service --property=LoadState,UnitFileState,ActiveState,SubState"
commands = command1 + "\n" + command2 + "\n" + command3

output = subprocess.check_output(commands, shell=True).decode()

end_time = time.time()

print(end_time-start_time)

实际代码有很多服务,并且这些代码运行非常频繁。什么可以使此代码运行得更快?有没有其他方法可以更快地获取这些信息?

System: Debian-like Linux x64, Python: 3.9

标签: pythonpython-3.xlinuxservicesystemd

解决方案


推荐阅读