Python 如何在Linux中检查脚本是否运行
Python中的 psutil 模块帮助我们获取关于正在运行在本地系统中的进程的信息。
什么是脚本
脚本是一组以编程语言编写的指令,然后在计算机上执行的指令。我们可以在较短的时间内执行各种简单到复杂的重复任务。在Linux中,脚本经常通过命令行使用Bash或Python解释器执行。这些脚本也可以被安排在特定时间运行,使用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
示例
在这个示例中,我们将使用子进程模块来检查脚本是否在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")
输出
以下是子进程的输出,用于检查进程是否正在运行。
The script is not running
示例
让我们看另一个例子,使用子进程模块在Linux中检查php脚本是否正在运行。
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语言的子进程模块的输出。
The script is not running