pythonjupyter-notebookipythonjupytergoogle-colaboratory

How to suppress output in Google Colaboratory cell which executes a command line script (line starts with `!`) via a function


In Google colab I execute command line scripts by place a ! in front of the line and executing the cell.

For example

!pip install adjustText

If I want to prevent output of this cell, I can do this

%%capture
!pip install adjustText

However, I have a situation where I execute the command line scripts via a function, and suppress output for that command line only, without suppressing the output of the cell from which it's being executed

For example

Cell1:

%%capture
def installAdjust():
    !pip install adjustText

Cell2:

for v in range(10):
    print(v)
    installAdjust()

This does not suppress the output from !pip install adjustText. I do not want to suppress the non-command line output from Cell2, so I can Not do this

Cell2:

%%capture
for v in range(10):
    print(v)
    installAdjust()

Also, this doesn't work either

Cell1:

def installAdjust():
   %%capture
    !pip install adjustText

Solution

  • Use capture_output from python's utilities:

    from IPython.utils import io
    for v in range(10):
        print(v)
        with io.capture_output() as captured:
          installAdjust()
    

    For the future, whenever a magic function doesn't suffice, search for the core properties being accessed and access them yourself.

    Answer sourced from: How do you suppress output in IPython Notebook?