在Python中调用UNIX命令(nice,renice)

时间:2015-04-12 16:13:06

标签: python linux unix

我正在制作一个Python程序,为流程分配新值并动态监控它们:

import os
import subprocess
#!/usr/bin/env python
print "hello world"
os.system("ps lx")
print "Enter PID"
pid = raw_input()
print "Entered PID",pid
print "Enter new priority"
new = raw_input()
print "Entered new priority is"new
os.system("sudo renice new pid")

我不知道如何使用Python中的参数调用nicerenice

1 个答案:

答案 0 :(得分:2)

使用subprocess

from subprocess import Popen,PIPE

p = Popen(["sudo","-S", "renice",new , pid], stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.write("password\n")

您也可以使用subprocess.check_call

from subprocess import Popen, PIPE,check_call

check_call(["ps", "lx"])
pid = raw_input("Enter PID")
print "Entered PID",pid
new = raw_input("Enter new priority")
print "Entered new priority is",new

p = Popen(["sudo","-S", "renice", new, pid], stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.write("pc160780\n")
out, err = p.communicate()

print(out if out else err)