SieuTruc
SieuTruc

Reputation: 495

how to get output of grep command (Python)

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 

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()

But the result is empty string.

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

Upvotes: 8

Views: 32246

Answers (3)

Sunghyun Kim
Sunghyun Kim

Reputation: 65

Another solution, try Plumbum package(https://plumbum.readthedocs.io/):

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

Upvotes: 2

Wolph
Wolph

Reputation: 80031

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

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()

Upvotes: 3

Gilles Quénot
Gilles Quénot

Reputation: 185179

Try that :

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

Upvotes: 13

Related Questions