239 words
1 minute
Turning off the annoying stdout messages from TensorFlow 2.0rc

Disclaimer: I only use the GPU version of TensorFlow v2.0.0-rc1, so I don’t know if this works with other versions.

When writing TensorFlow code in Python scripts and running the scripts in a terminal, we usually get a bunch of messages in stdout. The messages log information from the initialization stage of TensorFlow. These messages are annoying to many people. The messages come from both the underlying C++ code and the Python code of TensorFlow. So we need to disable the two sources in different ways. If we install TensorFlow through conda or pip, then the C++ code is already compiled, and we don’t have any way to modify the C++ source code. Fortunately, the messages coming from this source can be controlled by an environment variable, TF_CPP_MIN_LOG_LEVEL. In Linux, before running Python scripts, we can simply do something like $ export TF_CPP_MIN_LOG_LEVEL=2. But I prefer to hard-code this environment variable in my Python scripts because I’m lazy. I add the following code in my Python scripts before the code uses any TensorFlow object or function:

import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"

This code does not necessarily need to be placed before import tensorflow. But it must be placed before the code encounters any object or function coming from TensorFlow. I think the initialization of the TensorFlow package does not happen before this point. The second source of the messages can be turned off by the standard Python logging system:

import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
logging.getLogger("tensorflow").addHandler(logging.NullHandler(logging.ERROR))
Written content, images, and videos in this post are licensed under CC BY-NC-SA 4.0 . Code snippets are licensed separately under BSD 3-Clause .