将bash命令的输出保存到if..else语句中的变量中

时间:2015-04-03 00:06:41

标签: python linux variables command output

我有以下功能:

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中,因为它在我的函数中?或者,使用子进程只需一次调用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"

1 个答案:

答案 0 :(得分:2)

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]])