Running and Editing Python Scripts
IPython makes scripts a first-class part of the interactive workflow. The %run magic executes a Python file exactly as the interpreter would — importing it into the __main__ namespace — but with IPython's enhancements intact, and then hands control back so you can poke at the variables, functions, and classes the script defined.
Running a Script
Consider a file weights.py that computes a weighted average:
# weights.py
def weighted(values, factors):
return sum(v * f for v, f in zip(values, factors)) / sum(factors)
if __name__ == "__main__":
print(round(weighted([82, 90, 71], [0.2, 0.5, 0.3]), 2))
Run it from the shell and the function becomes available for further experimentation:
In [1]: %run weights.py
83.6
In [2]: weighted([10, 20], [1, 3])
Out[2]: 17.5
Arguments after the file name are passed to the script as if it were launched with python, and %run -i passes the current namespace, letting the script see your interactive variables. To restart a script cleanly after editing, run it again — with the %run default each re-run re-executes every line.
Editing Scripts from the Shell
%edit (or %ed) opens your system editor on a file — or on the most recent input block when given no argument — runs it on save, and reloads the result. In a notebook, the built-in cell editor replaces it. A common loop: edit, run, inspect, repeat.
In [3]: %edit weights.py # opens $EDITOR, runs file after save
In [4]: %alias # list shell shortcuts; %edit accepts file or block
Inspecting Failure
When a script raises an exception, IPython prints the classic detailed traceback with frames, and %debug drops you into the interactive debugger at the failing line so variables can be inspected live:
In [5]: %run bad_div.py
ZeroDivisionError: division by zero
In [6]: %debug
> /tmp/bad_div.py(3)<module>()
1 a = 1
...
ipdb> a/b
Summary
%run script.py args executes a file with IPython enhancements and imports its names, %edit round-trips files through your editor, and %debug turns an ordinary traceback into live post-mortem inspection.