在 Google Colab 上的 Jupyter Notebooks 中,使用 % 和 ! 运行 一个 shell 命令?
In Jupyter Notebooks on Google Colab, what's the difference between using % and ! to run a shell command?
问题在标题里
我知道%
通常表示IPython中的"magic variable"。这不是我非常熟悉的概念,但我已经阅读过它。
然而,今天我看到了一个教程,其中有人使用它来 运行 一个 shell 命令。通常我已经看到并使用了!
。
有区别吗?当我尝试时,两者似乎都在做同样的事情。
区别是这样的:
当你运行一个带有!
的命令时,它直接在子shell中执行一个bash命令。
当您 运行 带有 %
的命令时,它会执行 IPython 中定义的 magic commands 之一。
IPython定义的一些魔术命令故意镜像bash命令,但它们在实现细节上有所不同。
例如,运行使用 !cd
bash 命令不会持续更改您的目录,因为它 运行 在临时子 shell 中。但是,运行使用 %cd
魔术命令会持续更改您的目录:
!pwd
# /content
!cd sample_data/
!pwd
# /content
%cd sample_data/
!pwd
# /content/sample_data
在 IPython: Built-in Magic Commands 阅读更多内容。
问题在标题里
我知道%
通常表示IPython中的"magic variable"。这不是我非常熟悉的概念,但我已经阅读过它。
然而,今天我看到了一个教程,其中有人使用它来 运行 一个 shell 命令。通常我已经看到并使用了!
。
有区别吗?当我尝试时,两者似乎都在做同样的事情。
区别是这样的:
当你运行一个带有
!
的命令时,它直接在子shell中执行一个bash命令。当您 运行 带有
%
的命令时,它会执行 IPython 中定义的 magic commands 之一。
IPython定义的一些魔术命令故意镜像bash命令,但它们在实现细节上有所不同。
例如,运行使用 !cd
bash 命令不会持续更改您的目录,因为它 运行 在临时子 shell 中。但是,运行使用 %cd
魔术命令会持续更改您的目录:
!pwd
# /content
!cd sample_data/
!pwd
# /content
%cd sample_data/
!pwd
# /content/sample_data
在 IPython: Built-in Magic Commands 阅读更多内容。