Python and reading lines
-
13-09-2019 - |
Question
When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!
Solution
Really simple Python solution:
def getSummary(s):
return s[s.find('\nSummary'):]
This returns everything after the first instance of Summary
If you need to be more specific, I'd recommend regular expressions.
OTHER TIPS
actually
program.exe | grep -A 1 Summary
would do your job.
If the exe prints to screen then pipe that output to a text file. I have assumed the exe is on windows, then from the command line:
myapp.exe > output.txt
And your reasonably robust python code would be something like:
try:
f = open("output.txt", "r")
lines = f.readlines()
# Using enumerate gives a convenient index.
for i, line in enumerate(lines) :
if 'Summary' in line :
print lines[i+1]
break # exit early
# Python throws this if 'Summary' was there but nothing is after it.
except IndexError, e :
print "I didn't find a line after the Summary"
# You could catch other exceptions, as needed.
finally :
f.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow