pythonpython-3.xshellgoogle-colaboratory

What is the difference between starting a command with an ! and starting a command with % in Google Colab? !<command> or %<command>


If I open a Python 3 notebook in Google Colab and I run:

!pwd
!cd ..
!pwd

I get:

/content
/content

Whereas running:

!pwd
%cd ..
!pwd

Results in:

/content
/
/

What's the difference between the execution of !some command and %some command?


Solution

  • A bang ! open a new process before calling that command.

    So, a !cd won't change your current process. After it has run, you return back to where you were.

    %cd is a magic (there are a few others) that do what you want.

    So, normally you will use ! for most of your linux commands. Except a few magics that you will use occationally e.g. %cd, %env