Syntax#
This section covers common ipython features such as the ability to use ipython magic.
Embeded magics#
Note that you can embed line-based magic in Python code.
The following code stores the results of the %ls magic in the result variable.
result = %ls
print(result)
magics.ipynb
None
Python variables#
You can embed Python variables in bash expressions precending them with the $ sign. The variable’s value will then be substituted into the bash command and executed.
The following cell defines the dir_name variable and creates a folder based on the specified in the dir_name value.
dir_name = "/tmp/dir_from_variable"
!mkdir $dir_name
Next code insures that the directory specified in the dir_name really created.
!ls /tmp | grep dir_from_variable
dir_from_variable
The next cell substitutes the dir_name in order to delete the directory that was created earlier.
!rm -rf $dir_name
Omit %#
If you don’t have a corresponding name in the namespace, you can omit the % to call linebase magic.
For example the following cell applies timeit to the list generator and calls it just by name without any prefixes.
timeit [i for i in range(1000)]
23.6 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
Note: Magics cannot be called without % if they are in the nested namespace. The following cell tries to refer to the pwd magic inside the if block, causing an error.
try:
if True: res = pwd
except Exception as e:
print(e)
name 'pwd' is not defined
But the same syntax, but forcing the interpreter to use magic, works fine.
if True: res = %pwd