首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:对subprocess.call / subprocess.Popen来说很好吗?

Python:对subprocess.call / subprocess.Popen来说很好吗?
EN

Stack Overflow用户
提问于 2009-11-06 18:44:01
回答 3查看 31K关注 0票数 45

我需要限制使用subprocess.call从python进程中生成的外部命令行应用程序占用的时间和cpu,主要是因为有时产生的进程被卡住并将cpu固定在99%。

友好和超限似乎是实现这一目标的合理方法,但我不确定它们将如何与子进程交互。

限制是这样的:如果花费超过60秒的时间,cpu

  • 限制在20%的时间内,
  • 会杀死这个过程

我想将资源限制应用于子进程,而不是用于生成subprocesses.的进程

有没有一种方法可以对subprocess.call生成的进程应用nice和ulimit?有没有更好的蟒蛇本地替代品?

这是在linux (ubuntu)系统上。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-11-06 19:28:06

可以使用ulimitnice shell命令为子进程设置限制,如下所示:

代码语言:javascript
复制
import subprocess
subprocess.Popen('ulimit -t 60; nice -n 15 cpuhog', shell=True)

这运行cpuhog的60秒的CPU时间和一个良好的调整15。请注意,没有简单的方法来设置一个20%的CPU节流阀。该进程将使用100%的CPU,除非另一个(不太好的)进程也需要CPU。

票数 11
EN

Stack Overflow用户

发布于 2009-11-06 19:59:22

将preexec_fn参数用于subprocess.Popen和资源模块。示例:

parent.py:

代码语言:javascript
复制
#!/usr/bin/env python

import os
import sys
import resource
import subprocess

def setlimits():
    # Set maximum CPU time to 1 second in child process, after fork() but before exec()
    print "Setting resource limit in child (pid %d)" % os.getpid()
    resource.setrlimit(resource.RLIMIT_CPU, (1, 1))

print "CPU limit of parent (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p = subprocess.Popen(["./child.py"], preexec_fn=setlimits)
print "CPU limit of parent (pid %d) after startup of child" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)
p.wait()
print "CPU limit of parent (pid %d) after child finished executing" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)

child.py:

代码语言:javascript
复制
#!/usr/bin/env python

import os
import sys
import resource

print "CPU limit of child (pid %d)" % os.getpid(), resource.getrlimit(resource.RLIMIT_CPU)

parent.py将进入一个新的进程。在新的过程中,它将调用setlimits(),然后调用exec child.py。这意味着资源将在子进程中受到限制,而不是在父进程中。

运行程序时输出:

代码语言:javascript
复制
./parent.py
CPU limit of parent (pid 17404) (-1, -1)
Setting resource limit in child (pid 17405)
CPU limit of parent (pid 17404) after startup of child (-1, -1)
CPU limit of child (pid 17405) (1, 1)
CPU limit of parent (pid 17404) after child finished executing (-1, -1)

在许多情况下,这是一个比尝试使用ulimit更好的解决方案,因为通过shell生成子进程并不总是一个好主意,特别是因为它经常会导致丑陋的参数引用麻烦。

票数 118
EN

Stack Overflow用户

发布于 2014-04-06 08:12:15

Erik让我很轻松,但他忘记了Rich指出的nice部分。我觉得psutil包不错(双关意),但不幸的是它的便携性较低。以下是我对这个问题的看法:

代码语言:javascript
复制
import os
import psutil
import resource
import subprocess

def preexec_fn():
    pid = os.getpid()
    ps = psutil.Process(pid)
    ps.set_nice(10)
    resource.setrlimit(resource.RLIMIT_CPU, (1, 1))

print "mother pid", os.getpid()
p = subprocess.Popen(["./cpuhog.sh"], preexec_fn=preexec_fn)
p.wait()
print "mother still alive with pid", os.getpid()

Ville使用了我对其过敏的shell=True。也许我只是老了,脾气暴躁,但我尽量避免它!

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1689505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档