[Python] How to Use IPython Magic Commands (Magic Functions)

IPython provides a set of convenient commands called “Magic Functions” for measuring code execution time or manipulating external files. These are executed by prefixing them with %.

目次

List of Main Magic Commands

Magic FunctionRoleParameter Example
%timeitMeasures execution time of code (calculates average over multiple runs).%timeit range(100)
%runExecutes an external Python script file.%run script.py
%historyDisplays input history so far.%history -n 1-5
%saveSaves history of specified lines to a file.%save file.py 1-10
%loadLoads code from an external file into the current input cell.%load script.py
%pwdDisplays the current working directory (path).%pwd
%lsDisplays a list of files in the current directory.%ls

Execution Examples

1. Measuring Code Execution Time (%timeit)

Automatically loops the specified code multiple times to calculate the most accurate average execution time.

In [1]: %timeit list(range(1000))
9.85 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

2. Executing External Scripts (%run)

Executes a .py file located in the current directory within the IPython environment. Variables after execution remain accessible within IPython.

sample.py (File created in advance)

print("This is a sample script.")
message = "Hello from script!"

Execution in IPython

In [2]: %run sample.py
This is a sample script.

In [3]: print(message)
Hello from script!

3. Referencing and Saving History (%history, %save)

You can check code entered in the past or select specific lines to save to a file.

# Execute some code
In [4]: s = "sample string"
In [5]: print(s)
sample string

# Check history (Display all without options)
In [6]: %history
%timeit list(range(1000))
%run sample.py
print(message)
s = "sample string"
print(s)

# Save specific lines (lines 4 and 5) to 'sample2.py'
In [7]: %save sample2.py 4 5
The following commands were written to file 'sample2.py':
s = "sample string"
print(s)

4. Loading Code (%load)

Expands the content of a file into the current cell. This is convenient when you want to check or edit the content before execution.

In [8]: %load sample2.py

# When executed, the cell content changes as follows:
# %load sample2.py
s = "sample string"
print(s)

Supplement: Line Magic and Cell Magic

  • Line Magic (%): Commands effective for a single line. (Example: %timeit)
  • Cell Magic (%%): Commands effective for the entire cell. (Example: Writing %%timeit measures the time for the entire multi-line code in that cell.)
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次