如何获取grep命令的输出(Python)

时间:2012-10-09 22:43:59

标签: python grep subprocess

我有一个输入文件test.txt:

host:dc2000
host:192.168.178.2

我希望使用以下方法获取这些机器的所有地址:

grep "host:" /root/test.txt 

依此类推,我通过python获取命令输出:

import subprocess
file_input='/root/test.txt'
hosts=subprocess.Popen(['grep','"host:"',file_input], stdout= subprocess.PIPE)
print hosts.stdout.read()

但结果是空字符串。

我不知道我遇到了什么问题。你能建议我怎么解决吗?

3 个答案:

答案 0 :(得分:5)

试试:

import subprocess
hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
print hosts

答案 1 :(得分:2)

您的代码应该有效,您确定该用户具有读取文件的访问权限吗?

另外,您确定文件中有"host:"吗?你的意思可能是:

hosts_process = subprocess.Popen(['grep','host:',file_input], stdout= subprocess.PIPE)
hosts_out, hosts_err = hosts_process.communicate()

答案 2 :(得分:1)

另一种解决方案,请尝试使用Plumbum软件包(https://plumbum.readthedocs.io/):

from plumbum.cmd import grep print(grep("host:", "/root/test.txt")) print(grep("-n", "host:", "/root/test.txt")) #'-n' option