将 bash 命令的输出保存到 if..else 语句中的变量中
Save output of bash command into variable inside if..else statement
我有以下功能:
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]])
我有以下功能:
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]])