Reputation: 18353
I know how to do this with a file, you just do file = file.open(f) f
file = open("file.txt")
for line in file.readlines():
if line.startswith("foo"):
print line
But now I'm reading the output of a process like this
log = os.popen("log.sh").read()
This outputs as a string, which can be used with print fine, but if I do a "for line in log" it splits each character, not line. And, being a string, there is no .readlines() attribute.
My end goal is to be able to "grep" for a revision number in the log and print the line (and above and below)
Upvotes: 1
Views: 3729
Reputation: 500437
You have several options:
Option 1:
log = os.popen("log.sh").readlines()
This gives a list of string that you can process exactly like you do when reading a file.
Option 2:
log = os.popen("log.sh").read()
for line in log.splitlines(True):
...
Upvotes: 6
Reputation: 601789
for line in log.splitlines():
# whatever
Note that you don't need to use f.readlines()
for a file f
.
for line in f:
# whatever
will work fine.
Upvotes: 9