我有一个带有特殊数学计算器的网站(Ubuntu OS 和 Apache 服务器上的 Wordpress 网站),其中许多使用 python3 脚本进行主要计算。这些计算器上的数据流如下:
1.) 用户在 html 表单中输入数字,然后点击提交按钮。
2.)调用PHP函数,它将html用户输入分配给变量,并使用这些变量对适用的python3文件执行exec()(过滤用户输入并使用escapeshellarg,所以在这里一切都很好)。
3.) PHP 函数返回 python3 脚本的结果,通过简码显示在计算器网页上。
我遇到的问题是,有时我的 python 脚本中的符号和数字计算会无限期地挂起。随着那个 python3 进程继续运行,它开始使用大量的 CPU 和内存资源(在高峰流量时间是个大问题)。
我的问题是:是否有某种方法可以在我的服务器后端创建一个脚本或程序,如果它超过了任意运行时和 CPU 使用级别,它将杀死 python3 的进程实例?我想把它限制在python3的实例中,这样它就不能杀死像mysqld这样的东西。另外,如果它只使用运行时作为终止条件,我也可以。在正常情况下,我的任何 python 脚本的运行时间都不应超过 ~10 秒,如果它们的运行时间不超过 10 秒,CPU 使用率不会成为问题。
最佳答案
您可以根据 psutil 创建另一个 python 脚本作为服务器上的健康检查器。和 os模块。
以下代码可以作为您特定需求的基础,注意它的作用基本上是检查 script_name_list
上的 python 脚本的 PID。基于脚本名称的变量,并在检查服务器的 CPU 是否高于某个阈值或可用内存是否也低于某个阈值后将其杀死。
#!/usr/bin/env python3
import psutil
import os
import signal
CPU_LIMIT = 80 #Change Me
AV_MEM = 500.0 #Change Me
script_name_list = ['script1'] #Put in the name of the scripts
def find_other_scripts_pid(script_list):
pid_list = []
for proc in psutil.process_iter(['pid','name', 'cmdline']):
#this is not the PID of the process referencing this script and therefore we chould check inside the list of script name to kill them
if proc.info['pid'] != os.getpid() and proc.info['name'] in ['python','python3']:
for element in proc.info['cmdline']:
for script_name in script_name_list:
if script_name in element:
pid_list.append(proc.info['pid'])
return pid_list
def kill_process(pid):
if psutil.pid_exists(pid):
os.kill(pid,signal.SIGKILL)
return None
def check_cpu():
return psutil.cpu_percent(interval=1)
def check_available_memory():
mem = psutil.virtual_memory()
return mem.available/(2**(20))
def main():
cpu_usage = check_cpu()
av_memory_mb = check_available_memory()
if cpu_usage > CPU_LIMIT or av_memory_mb < AV_MEM:
pid_list = find_other_scripts_pid(script_name_list)
for pid in pid_list:
kill_process(pid)
if __name__ == "__main__":
main()
之后,您可以使用 crontab 在您的服务器上定期运行此脚本,如 post 中所述。在社区内共享。
关于python - 如何杀死超过 Linux 中 CPU 使用率和运行时限制的特定进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62583117/