如何限制python进程上的CPU周期和内存

问题描述

我想运行一个简单的python服务器,它将python代码作为字符串输入。我需要在 python 中使用 eval()exec() 运行输入字符串。 (在下面的示例代码中,我还没有添加 eval() 部分,它会进入 task()

但我正在寻找一种方法,通过提供 1% 的 cpu 和 1% 的内存来限制每个用户。我尝试过资源包 (https://docs.python.org/3/library/resource.html)。这似乎为整个 python 代码设置了限制(不仅仅是我正在运行的进程)

这是我作为 POC 尝试过的。如果您有好的建议,请告诉我。谢谢

def task():
    soft,hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS,(1024,hard))
    s = "helloworld"
    for j in range(1,10):
        s = s + s        
    print("Executors in process {}",format(os.getpid()))

def main():
    executor = ProcesspoolExecutor(max_workers=3)
    task1 = executor.submit(task)
    task2 = executor.submit(task)

if __name__ == '__main__':
    for i in range(1,10):
        main()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)