2012-10-09 53 views
3

我有一个输入文件test.txt作为输出: 主持人:DC2000 主持人:192.168.178.2如何获得grep命令(Python)的

我想通过使用获得所有这些机器的地址:

grep "host:" /root/test.txt 

等等,我通过Python get命令输出中:

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

但结果是空字符串。

我不知道我得到了什么问题。你能告诉我如何解决?

回答

3

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

另外,你确定文件中有一个"host:"?你可能意味着这个:

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

它工作,我让''主机:''到'主机:'。谢谢你 – SieuTruc

+0

@Shai:是的,你说得对。该示例最多不完整 – Wolph

+0

@Wolph感谢修复 – Shai

5

试一下:

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

,谢谢你的第二个解决方案 – SieuTruc

+0

是有可能,'check_output'抛出'subprocess.CalledProcessError'异常,如果'grep'没有发现该文件中的字符串的发生? – Shai