How to suppress output in Google Colaboratory cell which executes a command line script (line starts with `!`) via a function
Solution 1
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?
Solution 2
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
Peter Force
Updated on June 08, 2022Comments
-
Peter Force almost 2 years
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 thisCell2:
%%capture for v in range(10): print(v) installAdjust()
Also, this doesn't work either
Cell1:
def installAdjust(): %%capture !pip install adjustText
-
Jinhua Wang about 4 yearsWow this answer saved my day!
-
NeStack over 2 yearsHm, this doesn't work for me, I still get the output printed below the cell. Do I have to reload the notebook or something?
-
bhanu pratap over 2 yearsNot actually, it works for me even without reloading the notebook, What specifically you run?