1

I have the following particular question about pytest. During collection, stdout is filled with a lot of useless, maybe sensitive information (in the following example abstracted by print(1)). Therefore, I don't want this information to show up in pytest's "Captured stdout" output, in case an error happens during collection (in the following example a ZeroDivisionError). However, there is also useful information in stdout (in the following example abstracted by print(2)). So my idea was to just access stdout in between.

Inside a test function, I can use the capsys fixture to access the captured stdout as described here in the pytest docs. What can I use in my case outside a test function, during collection?

Example test.py, even without any actual test functions:

print(1)
# access stdout here
print(2)
1/0 # arbitrary error

Call to pytest:

$ python3 -m pytest test.py 
============================= test session starts ==============================
platform linux -- Python 3.6.7, pytest-4.5.0, py-1.8.0, pluggy-0.11.0
rootdir: /home/user/Documents
collected 0 items / 1 errors                                                   

==================================== ERRORS ====================================
___________________________ ERROR collecting test.py ___________________________
test.py:4: in <module>
    1/0
E   ZeroDivisionError: division by zero
------------------------------- Captured stdout --------------------------------
1
2
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.07 seconds ============================

As you can see, both 1 and 2 are captured. I want to clear stdout in between, so only 2 will show up. I mean, the captured stdout has to be stored by pytest somewhere, right? I just don't know how to access it, to clear it.

finefoot
  • 9,914
  • 7
  • 59
  • 102
  • 1
    Can you describe what you are trying to achieve by clearing the output of a particular print function? This is a strange thing you are requesting and I doubt there are very many valid use cases. What's so bad about `1` showing up in the output? – mario_sunny Nov 03 '19 at 17:17
  • Try these [stackoverflow](https://stackoverflow.com/questions/2084508/clear-terminal-in-python) – Brian Feb 28 '20 at 19:06
  • How about this [stackoverflow](https://stackoverflow.com/questions/56187165/how-to-clear-captured-stdout-stderr-in-pytest)? – Brian Feb 28 '20 at 19:13
  • Can you just [capture stdout](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) then dispose or keep it as you wish? – Brian Feb 28 '20 at 19:45

0 Answers0