I've been running in circles, trying to find a way to solve this.
I run a script, which call pytest
; which produce some output in terminal. The idea is to get this output, and put it in a variable, so I can either save it to a file, print it somewhere (like in a tkinter label object for example, if I ever plan to make the script part of a UI).
I did find about sys.stdout; but it seems that it is used TO print on screen (console in this case); which is not what I am looking for. I am trying to read what is sent to the console and printed.
The only solution so far is to do a redirect from the shell, when I call the python script; which sadly is not really an option for me, considering that I don't need the whole output of all that I do in that script, but only the output of pytest
, so stdout and stderr.
I assume that the data is buffered somewhere and then sent out for print on screen, although I did try to use sys.stdout
without luck.
There is a section in the pytest docs that mention capturing stdout/stderr, but either they didn't include some important details, or I am not able to understand how this works
def test_myoutput(capsys): # or use "capfd" for fd-level
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.err == "world\n"
print("next")
captured = capsys.readouterr()
assert captured.out == "next\n"
From this except, there is this object called capsys
, which has a property called readouterr()
, which should output errors (and I assume there is an equivalent for stdout); although capsys seems to not be part of pytest at all.
Any suggestion would be really appreciated.