views:

190

answers:

4

I know about os.nice() it works perfect for parent process, but I need to do renice of my child subprocesses. I found way to do this, but it seems to be not very handy and too excessive:

os.system("renice -n %d %d" % ( new_nice, suprocess.pid ) )

And it isn't return resulting nice level after renicing.

Is there more clean way to renice subprocesses in python?

+2  A: 

You should use subprocess.Popen instead of os.system, so you can access any results printed to sys.stdout. IIRC, os.system only gives you access to the return value, which is probably '0' and not the nice level.

jcdyer
+2  A: 

renice is usually implemented by set/getpriority , which doesn't seem to have made it into the python os or posix module(yet?). So calling the renice system command seems like your best bet now.

As an alternative, you could os.nice the parent before you create a child process - which will inherit its parents nice value - and os.nice back again after you've created the child process.

nos
He could call setpriority/getpriority using ctypes.
Daniel Stutzbach
A: 

without proper rights you can renice only in one way

bluszcz
+1  A: 

Use the preexec_fn on subprocess

>>> Popen(["nice"]).communicate()
0
(None, None)
>>> Popen(["nice"], preexec_fn=lambda : os.nice(10)).communicate()
10
(None, None)
>>> Popen(["nice"], preexec_fn=lambda : os.nice(20)).communicate()
19
(None, None)
Nick Craig-Wood