Running & Editing Python Script
IPython - Running and Editing Python Scripts
Section titled “IPython - Running and Editing Python Scripts”While IPython excels at interactive exploration, you’ll often need to run code stored in .py files. IPython provides magic commands to facilitate this workflow.
Running Scripts with %run
Section titled “Running Scripts with %run”The %run magic command executes a Python script from within your current IPython session. Crucially, after the script finishes, any variables, functions, or classes defined in the script become available in your interactive namespace.
# Create a file named 'myscript.py' with the following content:# ```python# # myscript.py# message = "Hello from the script!"# def greet(name):# print(f"{message} Hello, {name}!")# ```
In [1]: %run myscript.py
In [2]: print(message)# Output: Hello from the script!
In [3]: greet("Alice")# Output: Hello from the script! Hello, Alice!Note: If %automagic is enabled (often the default), you might be able to omit the % and just type run myscript.py. However, explicitly using %run is clearer.
You can also pass command-line arguments to the script using %run:
# Modify 'myscript.py' to accept arguments:# ```python# # myscript.py# import sys# name = sys.argv[1] if len(sys.argv) > 1 else 'World'# print(f"Hello, {name}!")# ```
In [4]: %run myscript.py Bob# Output: Hello, Bob!
In [5]: %run myscript.py# Output: Hello, World!Editing Scripts with %edit
Section titled “Editing Scripts with %edit”The %edit magic command opens an external text editor to modify a file. Which editor is opened depends on your system’s configuration (often determined by the EDITOR environment variable).
When used with a filename (%edit myscript.py), it opens that specific file. After you save and close the editor, IPython can optionally execute the modified code.
In [6]: %edit myscript.py# This will open myscript.py in your default editor (e.g., nano, vim, Notepad).# Make changes, save, and close the editor.# IPython might prompt: "Execute updated code? [Y/n]:"# If you choose Y, the modified script runs.If you use %edit without a filename, IPython creates a temporary file, opens it in the editor, and executes the code from that temporary file after you close the editor. The code entered is also returned as the output.
In [7]: %edit# Opens a temporary file in the editor.# Enter: print("Code from temp file")# Save and close.
# Output:# Code from temp file# Out[7]: 'print("Code from temp file")'While %edit can be useful in terminal IPython sessions, when working in JupyterLab or Notebook, it’s often more convenient to edit .py files directly in the built-in text editor or use cell magic like %%writefile and %load.