0

For example, lets say I do this:

print("Blah blah blah")

Now I want to be able to read the contents of that line which was just outputted to console and store it in a variable

For example:

CODE:
def getPrintedLine(contents_of_line):
    # some code to find that line
print("Blah blah blah")
myVar = getPrintedLine("blah")
print(myVar)
OUTPUT:
Blah blah blah
Blah blah blah
Zeeen
  • 312
  • 1
  • 2
  • 13

2 Answers2

1

I think you can capture the output by overriding the sys.stdout with a io.StringIO

it would look something like this

import sys
import io

old_std_out = sys.stdout
capture_io = io.StringIO()
sys.stdout = capture_io 

print("what you want to print")

# get what you just printed
printed = capture_io.getvalue()

sys.stdout = old_std_out 
capture_io.close()    

see also: Python: Assign print output to a variable

Arturo
  • 171
  • 1
  • 17
1

There are several ways to do this, but the easiest is simply to override the print function.

std_print = print

stdout_data = []
def new_print(*data, **kwargs):
    stdout_data.append(" ".join(map(str, data)))

print = new_print

# PRINTING CODE GOES HERE

# restore print to normal
print = std_print

# carry on as normal from here

stdout_data contains everything that was printed (each element is a line).

Note: **kwargs is only necessary if your code uses the named arguments to the print function. You can ignore that data mostly when overriding (even if you do include the argument).

ComedicChimera
  • 466
  • 1
  • 4
  • 15