我需要限制量的时间和cpu采取通过外部命令行程序产卵我从python过程中使用子流程.呼叫,主要是因为有时产生的过程中得到困和销cpu在99%以上。

好的和限制似乎是合理的方式来做到这一点,但我不知道该怎么他们会互动与子流程.

  • 限制看起来是这样的:
    • 杀死的过程中,如果它采取多60秒
    • 它限于20%的cpu
  • 我想要应用的资源限制到子流程,不向python过程的产卵子过程.

有没有办法适用于好的和限制到子流程.呼叫催生一进程?是否有更好的巨蟒地选择?

这是一个linux(ubuntu)系统。

有帮助吗?

解决方案

你可以设定限制对于子流程与 ulimitnice 命令是这样的:

import subprocess
subprocess.Popen('ulimit -t 60; nice -n 15 cpuhog', shell=True)

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

其他提示

使用preexec_fn参数子流程.Popen,以及资源模块。例如:

parent.py:

#!/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:

#!/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.这意味着该资源将限于在孩子的过程,但不是在父母。

输出当运行程序:

./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)

这是在许多情况下,一种更好的解决方案,比试图使用限制,因为它并不总是一个很好的想法产卵子进程通过壳,特别是因为它经常会导致丑陋的参数引用的麻烦。

埃里克 由我来说很简单,但是他忘记了 nice 其中一部分 丰富 指出。我找到的 psutil 包装好(双关的目的),但不幸的是小便携式。这里是我需要的问题:

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 到哪我不知怎么过敏。也许我只是脾气暴躁的老在这里,但我尽量避免它!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top