如何存储在Python中的变量的执行shell命令的结果? [英] How to store the result of an executed shell command in a variable in python?

查看:533
本文介绍了如何存储在Python中的变量的执行shell命令的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储,我在一个变量执行的shell命令的结果。但我couldn得到。我想这样的:

I need to store the result of a shell command that I executed in a variable. But i couldn get that. I tried like:

call=os.system("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'")
print call

但它打印在终端的结果并打印通话的价值为零,这可能表明是成功。如何获得存储在一个变量的结果?

But it prints the result in terminal and prints the value of call as zero, possibly indicating as success. How to get the result stored in a variable?

推荐答案

使用 模块来代替:

Use the subprocess module instead:

import subprocess
output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)

编辑:这是新的Python 2.7。在早期版本中这应该工作(与改写如下图所示的命令):

this is new in Python 2.7. In earlier versions this should work (with the command rewritten as shown below):

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]


作为一个方面说明,你可以重写


As a side note, you can rewrite

cat syscall_list.txt | grep f89e7000

grep f89e7000 syscall_list.txt

和你甚至可以用一个 AWK 脚本替换整个语句:

And you can even replace the entire statement with a single awk script:

awk '/f89e7000/ {print $2}' syscall_list.txt

通往:

import subprocess
output = subprocess.check_output(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'])

这篇关于如何存储在Python中的变量的执行shell命令的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆