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 process gets stuck and pins the cpu at 99%.
nice and ulimit seem like reasonable ways to do this, but I'm not sure how they'd interact with subprocess.
- The limits look something like:
- Kill the process if it's taking more than 60 seconds
- Limit it to 20% of cpu
- I want to apply the resource limiting to the subprocess, not to the python process that's spawning the subprocesses.
Is there a way to apply nice and ulimit to the subprocess.call spawned process? Are there better python-native alternatives?
This is on a linux (ubuntu) system.
You can set limits for subprocesses with the
ulimit
andnice
shell commands like this:This runs
cpuhog
with a limit of 60 seconds of CPU time and a niceness adjustment of 15. Note that there is no simple way to set a 20% CPU throttle as such. The process will use 100% CPU unless another (less nice) process also needs the CPU.Erik made it easy for me, but he forgot the
nice
part which Rich Pointed out. I find thepsutil
package nice(pun intended) but unfortunately less portable. Here is my take at the question: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!Use the preexec_fn parameter to subprocess.Popen, and the resource module. Example:
parent.py:
child.py:
parent.py will fork into a new process. In the new process, it will call setlimits(), then exec child.py. This means the resource will be limited in the child process, but not in the parent.
Output when running program:
This is in many cases a better solution than trying to use ulimit, since it's not always a good idea to spawn subprocess via shell, especially since it often causes ugly parameter quoting trouble.