我有以下功能:
def check_process_running(pid_name):
if subprocess.call(["pgrep", pid_name]):
print pid_name + " is not running"
else:
print pid_name + " is running and has PID="
check_process_running(sys.argv[1])
如果我运行脚本,它将给我:
$ ./test.py firefox
22977
firefox is running and has PID=
我需要获得pid_num才能进一步处理该过程。我了解到,如果我想使用pid值为22977创建变量,则可以使用:
tempvar = subprocess.Popen(['pgrep', sys.argv[1]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
pid_num = tempvar.stdout.read()
print pid_num
22977
是否有解决方案,不需要构造tempvar,是否将pid拾取并保存到if..else语句中的pid_num变量中,就像在函数中一样?还是最简单的方法来创建pid_num变量,而只需使用子进程一次调用shell并使该函数保持现在的简单性即可?
编辑:
使用波纹管解决方案,我能够重建该语句,使其保持简单,并让pid_num进一步处理该过程:
def check_process_running(pid_name):
pid_num = subprocess.Popen(['pgrep', sys.argv[1]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
if pid_num:
print pid_name + " is running and has PID=" + pid_num
else:
print pid_name + " is not running"
pid_number = subprocess.Popen(['pgrep', sys.argv[1]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
可能是?也许更好
pid_number = subprocess.check_output(['pgrep', sys.argv[1]])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句