如何在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP