【问题标题】:Save output of bash command into variable inside if..else statement将 bash 命令的输出保存到 if..else 语句中的变量中
【发布时间】: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


    【解决方案1】:
    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]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2021-12-03
      • 2011-12-31
      • 2012-03-02
      • 2018-01-09
      • 2012-04-03
      • 1970-01-01
      相关资源
      最近更新 更多