pasting_code_snippets
Pasting Code Snippets
Section titled “Pasting Code Snippets”A common task when working interactively is copying code examples from websites, documentation, or other Python sessions and pasting them into your current IPython or Jupyter session. IPython is intelligent about handling common prompt prefixes found in such examples.
Pasting from Standard Python Shell (>>>, ...)
Section titled “Pasting from Standard Python Shell (>>>, ...)”If you copy code directly from a standard Python REPL session, including the >>> and ... prompts, IPython will automatically filter these out when you paste the code.
Consider this code copied from a standard Python shell:
>>> for i in range(3):... print(f"Number: {i}")...If you paste this directly into an IPython cell:
# Pasted content in IPython cell:>>> for i in range(3):... print(f"Number: {i}")...IPython will execute it as if you had typed:
for i in range(3): print(f"Number: {i}")Output:
Number: 0Number: 1Number: 2Pasting from Other IPython/Jupyter Sessions (In [...], ...:)
Section titled “Pasting from Other IPython/Jupyter Sessions (In [...], ...:)”Similarly, IPython can handle its own input prompts (In [N]:) and continuation prompts (...: or .:) when pasting code from another IPython session or Jupyter notebook.
Suppose you copy the following from another IPython session:
In [1]: def greet(name): ...: print(f"Hello, {name}!") ...:
In [2]: greet("Alice")Pasting this into a new IPython cell will correctly define the function and then call it, filtering out the In [...] and ...: prefixes.
# Pasted content in IPython cell:In [1]: def greet(name): ...: print(f"Hello, {name}!") ...:
In [2]: greet("Alice")
# Output:Hello, Alice!Magic Commands for Pasting
Section titled “Magic Commands for Pasting”IPython also offers magic commands related to pasting, although direct pasting is often sufficient:
%paste: Pastes clipboard content, attempting the same intelligent filtering of prompts.%cpaste: Opens a special prompt where you can paste code. It allows you to review/edit the code before executing it. Finish by typing--on a line by itself or hitting Ctrl-D.
# Example using %cpasteIn [3]: %cpastePasting code; enter '--' alone on the line to stop or use Ctrl-D.:>>> def add(x, y)::... return x + y:--
In [4]: add(5, 3)Out[4]: 8This intelligent pasting feature significantly streamlines the process of trying out code examples found online or shared by colleagues, making IPython and Jupyter very convenient for interactive exploration and learning.