Is it possible to somehow just capture the console output? Those. I need to copy, redirect or perform other actions so that I can work with this text (I just need to redirect it to a form in the program). It seems to be written with work through a file, but it seems to me that this is too complicated a decision, maybe it is easier?
- look subprocess, maybe it will help. - Sonic Myst
- Is the console output of another program or your script from the inside? - gil9red
- @ gil9red, my program is everything that it displays, through print, errors, etc. Just to output the program displayed in the right place for me. - sank
|
1 answer
Use the contextlib module:
from contextlib import redirect_stdout import io f = io.StringIO() with redirect_stdout(f): print('123') print('abc') s = f.getvalue() print(s) # 123 # abc Another example of manually catching exceptions and redirects to stderr:
from contextlib import redirect_stdout, redirect_stderr import io import sys import traceback f = io.StringIO() with redirect_stdout(f), redirect_stderr(f): try: print('123') print('abc') 1 / 0 except: print(traceback.format_exc(), file=sys.stderr) s = f.getvalue() print(s) # 123 # abc # Traceback (most recent call last): # File ..., line 18, in <module> # 1 / 0 # ZeroDivisionError: division by zero Ps.
To intercept stderr - redirect_stderr
- Thanks, it works, but correctly from the module. I'm a little harder - I invoke tests through cmd pytest commands. I see these findings in pycharm, and having acquired the test run method did not produce fruit (probably and expectedly). Is it possible to intercept such an option, or to wrap each module of the test? - sank
- If you call the tests from the py code by wrapping it
with redirect_stdout(f)it will work out, otherwise call it through the subprocess and read the data from it. You can also redirect the output stream to a file using the console. And maybe pytest can output to a file (I didn't work with it, just an assumption) - gil9red pm - @ gli9red, Thanks for your responses, but for now it doesn’t work. The construction in the main file is as follows: - sank
- self.f = io.StringIO (), declared in initialization
with redirect_stdout(self.f), redirect_stderr(self.f): try: os.system('cd all_tests & py -m pytest ' + x + ' -s -v') # --run_number=1 except: print(traceback.format_exc(), file=sys.stderr) s = self.f.getvalue() self.log_text.insert(END, s + '\nx')But so far it went around in the wrong way - pytests has a command --junitxml = logggGG.txt which unloads the entire log, but in xmk format. - sank
|