是的,在Linux中,可以使用Python命令行來進行性能監控
top命令:top命令是一個實時顯示系統進程信息的工具。在Python中,你可以通過調用subprocess模塊來運行top命令并獲取實時數據。例如:
import subprocess
def monitor_performance():
while True:
result = subprocess.run(['top', '-b'], capture_output=True, text=True)
print(result.stdout)
if __name__ == '__main__':
monitor_performance()
psutil庫:psutil是一個跨平臺的庫,可以方便地獲取系統進程和系統性能信息。首先,你需要安裝psutil庫:
pip install psutil
然后,你可以使用以下代碼來監控CPU和內存使用情況:
import psutil
def monitor_performance():
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_usage = psutil.virtual_memory().percent
print(f'CPU Usage: {cpu_usage}%, Memory Usage: {memory_usage}%')
if __name__ == '__main__':
monitor_performance()
htop命令:htop是一個增強版的top命令,提供了更友好的界面和更多的功能。首先,你需要安裝htop命令(在某些發行版中可能需要使用sudo apt-get install htop或sudo yum install htop)。
然后,你可以使用以下代碼來監控CPU和內存使用情況:
import subprocess
def monitor_performance():
while True:
result = subprocess.run(['htop', '-d', '1'], capture_output=True, text=True)
print(result.stdout)
if __name__ == '__main__':
monitor_performance()
這些方法可以幫助你在Linux中使用Python命令行進行性能監控。你可以根據自己的需求選擇合適的方法。