【发布时间】:2015-06-08 02:04:37
【问题描述】:
我有以下功能:
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 的解决方案,在 if..else 语句中提取 pid 并将其保存到变量 pid_num 中,就像在我的函数中一样?或者,使用 subprocess 只需一次调用 shell 即可创建 pid_num 变量并保持函数像现在一样简单的最直接方法是什么?
编辑:
通过以下解决方案,我能够重建语句,保持简单并让 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"
【问题讨论】:
标签: python linux variables command output