如何在 Linux 中使用 Python 檢查任何指令碼是否正在執行?


Python 中的psutil模組幫助我們檢索有關當前在本地系統中執行的程序的資訊。

什麼是指令碼?

指令碼是一組用程式語言編寫的指令,並在計算機上執行。我們可以用更短的時間執行各種簡單到複雜的重複性任務。在 Linux 中,指令碼通常透過命令列使用 Bash 或 python 等 shell 直譯器執行。這些指令碼還可以使用 cron 或systemd安排在特定時間執行。

安裝 psutil 模組

要使用 psutil 模組,首先我們必須檢查該模組是否已安裝。如果沒有,我們必須使用以下程式碼進行安裝。

pip install psutil

示例

在以下示例中,我們將一個指令碼(檔名)傳遞給使用者定義的函式 is_process_running()。如果腳本當前正在執行,則此函式返回 true。否則返回 false。

import psutil
def is_process_running(name):
    for process in psutil.process_iter(['name']):
        if process.info['name'] == name:
            return True
    return False
if is_process_running('script.py'):
    print('The script is running.')
else:
    print('The script is not running.')

輸出

The script is not running.

安裝 Sub process.run 模組

我們還有另一種方法來檢查指令碼是否在 Linux 中執行;使用 sub process.run 模組。但首先,我們必須在 python 環境中安裝 sub process.run 模組。

pip install subprocess.run

示例

在此示例中,我們將使用 sub process 模組檢查指令碼是否在 Linux 中執行。我們將在命令列中執行以下程式碼。

import subprocess
script_name = "sample.py"
ps_output = subprocess.check_output(["ps", "-ef"])
ps_lines = ps_output.decode("utf-8").split("\n")
for line in ps_lines:
    if script_name in line:
        print("The script is running")
        break
else:
    print("The script is not running")

輸出

以下是 subprocess 檢查程序是否正在執行的輸出。

The script is not running

示例

讓我們再看一個示例,以檢查 php 指令碼是否在使用 sub process 模組的 Linux 中執行。

import subprocess
script_name = "sample.php"
ps_output = subprocess.check_output(["ps", "-ef"])
ps_lines = ps_output.decode("utf-8").split("\n")
for line in ps_lines:
    if script_name in line:
        print("The script is running")
        break
else:
    print("The script is not running")

輸出

以下是 python 語言的 sub process 模組的輸出。

The script is not running

更新於: 2023-08-09

4K+ 閱讀量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.