subprocess : AttributeError: 'Popen' object has no attribute 'read'
Peter Otten
__peter__ at web.de
Fri Jan 4 09:05:26 EST 2019
Mohan Mohta wrote:
> Hello,
> I am trying to grep the keyword (which I got from report_file ) from
> report_file
>
> I tried multiple ways but am unable to get it to work.
>
> Below are the methods I tried.
>
> <Original Code>
> fp=open(txt_file,'r')
> for line in fp :
> line=line.strip()
> var1=line.lower()
> g_info=subprocess.Popen('cat report_file| grep -i '+var1,
> stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
> g_info=g_info.read() g_info=g_info.strip()
> info=g_info.strip('||')
> print g_info
> print info
> fp.close()
> Error:
> AttributeError: 'Popen' object has no attribute 'read'
You have to specify the stream/file, e. g.
g_info.stdout.read()
but when want both stdout and stderr your reading attempts may produce a
deadlock as the fine manual warns.
So with basic error checks:
import subprocess
def grep(file, wanted):
p = subprocess.Popen(
["grep", "-i", wanted, file],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = p.communicate()
if p.returncode:
raise Exception(stderr)
return stdout
txt_file = "wanted.txt"
report_file = "report.txt"
with open(txt_file) as fp:
for line in fp :
wanted = line.strip().lower()
print "Looking for:", wanted
print "Found:"
print grep(report_file, wanted)
> info=g_info.strip('||')
This does not do what you think it does -- it will remove all "|" chars from
the beginning and the end of the string, just like g_info.strip("|") and
g_info.strip("||||||||||||||||") would, i. e. the str.strip() argument is
treated like a set of chars.
More information about the Python-list
mailing list