Reputation: 4049
Both !
and %
allow you to run shell commands from a Jupyter notebook.
%
is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands.
!
, provided by Jupyter, allows shell commands to be run within cells.
I haven't been able to find much comparing the two, and for simple shell commands like cd
, etc. The main difference I see is that %
is interactive and will actually change your location in the shell while in the notebook.
Are there other points or rules of contrast when thinking about which symbol to use for shell commands in a Jupyter notebook?
Upvotes: 84
Views: 31966
Reputation: 2866
Simple difference
! is used for executing shell commands through Jupyter notebook, Jupyter notebook kernel communicates with systems shell
% is used for executing Jupyter-specific magic commands, this communicates directly with kernel
Upvotes: 0
Reputation: 101
The exclamation mark (!) executes shell commands within a Jupyter Notebook cell when you type (!) followed by a shell command, Jupyter Notebook sends the command to the shell to run, on the other hand, the percent symbol (%) is used to execute special commands, called "magic commands", that are specific to Jupyter Notebook and not valid as shell commands for example:%matplotlib inline to enable inline plots.
However, % is also capable of sending shell commands like "ls", "cd" or "pip install" to the Juypter Notebook to execute. One difference I noticed as well is that In the latter case "pip install" will target the active virtual environment associated with the Jupyter Notebook kernel while if I do "!pip install" visual studio code will complain asking to use % in order for the packages to be installed to the right virtual environment.
Upvotes: 6
Reputation: 6291
!
calls out to a shell (in a new process), while %
affects the process associated with the notebook (or the notebook itself; many %
commands have no shell counterpart).
!cd foo
, by itself, has no lasting effect, since the process with the changed directory immediately terminates.
%cd foo
changes the current directory of the notebook process, which is a lasting effect.
Upvotes: 106