如何获取grep命令的输出(Python) [英] how to get output of grep command (Python)

查看:76
本文介绍了如何获取grep命令的输出(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入文件test.txt为:

I have an input file test.txt as:

host:dc2000
host:192.168.178.2

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

I want to get all of addresses of those machines by using:

grep "host:" /root/test.txt 

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

And so on, I get command ouput via python:

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

但是结果是空字符串.

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

I don't know what problem I got. Can you suggest me how to solve?

推荐答案

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

Your code should work, are you sure that the user has the access right to read the file?

还可以确定文件中是否有"host:" ?您可能会这样说:

Also, are you certain there is a "host:" in the file? You might mean this instead:

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

这篇关于如何获取grep命令的输出(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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