如何使用Python检查Linux中是否运行任何脚本?如何使用Python检查Linux中是否运行任何脚本?如何使用Python检查Linux中是否运行任何脚本?如何使用Python检查Linux中是否运行任何脚本?
  • 文章
  • 正则表达式
    • 工具
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容
发表 admin at 2025年2月28日
类别
  • 未分类
标签

如何使用Python检查Linux中是否运行任何脚本?

Python 中的 psutil 模块帮助我们检索有关当前在本地系统中运行的进程的信息。

什么是脚本?

AScript 是一组用编程语言编写并在计算机中执行的指令。我们可以在更短的时间内执行各种简单到复杂的重复性任务。在 Linux 中,脚本通常使用 Bash 或 python 等 shell 解释器通过命令行执行。还可以使用 cron 或 systemd 安排这些脚本在特定时间运行。

安装 psutil 模块

要使用 psutil 模块,首先我们必须检查该模块是否已安装。如果没有,我们必须使用以下代码进行安装。

pip install psutil

例子

在下面的示例中,我们将脚本(文件名)传递给用户定义的函数 is_process_running()。如果脚本当前正在运行,则此函数返回 true。如果不是,则为假。

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 中运行;使用子 process.run 模块。但首先,我们必须在python环境中安装sub process.run模块。

pip install subprocess.run

例子

在本例中,我们将使用子进程模块检查脚本是否在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 脚本是否在 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
©2015-2025 艾丽卡 support@alaica.com