8

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?

3 Answers 3

13

Try that :

import subprocess
hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
print hosts
Sign up to request clarification or add additional context in comments.

1 Comment

is it possible that check_output throws subprocess.CalledProcessError exception if grep finds no occurrence of the string in the file?
3

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

1 Comment

@Shai: yes, you're right. The example was incomplete at best
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.