24

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
Peter Force
  • 439
  • 1
  • 5
  • 13

3 Answers3

35

you can use '%%capture' magic function in a cell(without quotes) to suppress the output of that particular cell whether it uses a command-line code or some python code, magic function is basically a property of jupyter notebooks but since google colab is built over this, it will work there also. eg:

%%capture
!wget https://github.com/09.10-20_47_44.png
bhanu pratap
  • 626
  • 7
  • 10
8

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?

Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
-1

Simply append to the command an output redirection:

Redirect output AND errors, add &> /dev/null

!mkdir /content/notexist/blah &> /dev/null

Redirect output, but NOT errors, add > /dev/null

!mkdir /content/notexist/yeaa > /dev/null

In the example below, both commands fail, but we ignore the error from the second.

enter image description here

Specifically for your case, the code would be:

%%capture
def installAdjust():
    !pip install adjustText &> /dev/null
Rub
  • 2,071
  • 21
  • 37