Python: ulimit and nice for subprocess.call / subprocess.Popen?

后端 未结 3 996
Happy的楠姐
Happy的楠姐 2020-12-12 14:03

I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned pro

3条回答
  •  甜味超标
    2020-12-12 14:17

    Erik made it easy for me, but he forgot the nice part which Rich Pointed out. I find the psutil package nice(pun intended) but unfortunately less portable. Here is my take at the question:

    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 used the shell=True to which I'm somehow allergic. Perhaps I'm just old and grumpy here, but I try to avoid it!

提交回复
热议问题