0

I'm trying to redirect some of the prints in a module, specifically keras-tuner, to a variable. It seems that there might be a similar solution: similar solution

from io import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio    # free up some memory
        sys.stdout = self._stdout

Then I wrapped around my code that has a module that prints, for example search_space_summary

with Capturing() as output:
    model_info["tuner"].search_space_summary()

However upon inspection there is nothing in output. But one can simply do a print("Hello") and it is captured in output, but not this function.

user1157751
  • 2,427
  • 6
  • 42
  • 73
  • @Carcigenicate I checked both stdout and stderr, but they are both empty. I might be wrong, but looking at the `patch` block, it seems that they are testing the output should be empty? – user1157751 Oct 08 '20 at 19:07
  • Interesting. At a glance, particularly reading [the definition of `search_space_summary`](https://github.com/keras-team/keras-tuner/blob/c23537d4bddd6cefb73b53d88dacaad1b48fc06f/kerastuner/engine/base_tuner.py#L266-L280) -- which is just doing plain `print` calls -- this _looks_ like it should work. – Charles Duffy Oct 08 '20 at 19:08
  • @CharlesDuffy All of the print statements in this module are not capture-able, very strange – user1157751 Oct 08 '20 at 19:13
  • ...I do notice that `from __future__ import print_function` is in use. Be interesting to look into just how that's implemented (if the Python runtime version in question is one where it isn't just a noop). On which point -- which runtime version _is_ this observed with? – Charles Duffy Oct 08 '20 at 19:16
  • @CharlesDuffy I'm using python 3.7.7 – user1157751 Oct 08 '20 at 19:45

1 Answers1

0

The keras-tuner package's util.py includes IPython/Jupyter notebook magic that displays custom output if a user is using a notebook and does not use the print function.

Hence there was not output.

user1157751
  • 2,427
  • 6
  • 42
  • 73