如何通过函数抑制执行命令行脚本(行以`!`开头)的 Google Colaboratory 单元中的输出

Pet*_*rce 11 python ipython jupyter jupyter-notebook google-colaboratory

在 Google colab 中,我通过在行!前放置 a并执行单元格来执行命令行脚本。

例如

!pip install adjustText
Run Code Online (Sandbox Code Playgroud)

如果我想阻止这个单元格的输出,我可以这样做

%%capture
!pip install adjustText
Run Code Online (Sandbox Code Playgroud)

但是,我有一种情况,我通过函数执行命令行脚本,并仅抑制该命令行的输出,而不抑制正在执行它的单元格的输出

例如

单元格 1:

%%capture
def installAdjust():
    !pip install adjustText
Run Code Online (Sandbox Code Playgroud)

单元格2:

for v in range(10):
    print(v)
    installAdjust()
Run Code Online (Sandbox Code Playgroud)

这不会抑制!pip install adjustText. 我不想抑制 Cell2 的非命令行输出,所以我不能这样做

单元格2:

%%capture
for v in range(10):
    print(v)
    installAdjust()
Run Code Online (Sandbox Code Playgroud)

此外,这也不起作用

单元格 1:

def installAdjust():
   %%capture
    !pip install adjustText
Run Code Online (Sandbox Code Playgroud)

小智 25

您可以在单元格中使用 '%%capture' 魔术函数(不带引号)来抑制该特定单元格的输出,无论它使用命令行代码还是某些 python 代码,魔术函数基本上是 jupyter notebooks 的一个属性,但由于谷歌colab 是建立在这个之上的,它也可以在那里工作。例如:

%%capture
!wget https://github.com/09.10-20_47_44.png
Run Code Online (Sandbox Code Playgroud)


Yaa*_*ler 7

使用capture_output从Python的工具:

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

对于未来,每当魔术函数不够用时,搜索正在访问的核心属性并自己访问它们。

答案来自:如何抑制 IPython Notebook 中的输出?