Sub topic 12
Dropping into the Shell After a Script with python -i and PYTHONSTARTUP
This chapter assumes you can run python3 from a terminal, write functions and loops, and read a traceback. You already know how to type code at the >>> prompt. Now you will load a script's results into that prompt and set up a prompt that is ready the moment it opens.
Running a script, then keeping the shell
Normally python3 script.py runs the file and exits. Its variables disappear with the process. The -i option (interactive) changes that: Python runs the script, then opens the prompt in the same namespace.
Suppose stats.py contains this:
data = [3, 1, 4, 1, 5]
def mean(values):
return sum(values) / len(values)
print("loaded", len(data), "values")Start it with -i:
python3 -i stats.pyThe script's print runs first. Then the prompt appears, and data and mean are already defined:
loaded 5 values
>>> mean(data)
2.8
>>> data.append(9)
>>> mean(data)
3.6666666666666665This is faster than pasting a script into the shell, and nothing needs importing. You edit the file, quit, and start again.
Inspecting a crash with -i
With -i, the shell also opens when the script ends with an uncaught exception. Python prints the traceback, then gives you a prompt. The variables are still there, so you can inspect the state at the moment of failure.
rows = [10, 20, 0]
for r in rows:
print(100 / r)Save this as fail.py and run python3 -i fail.py:
10.0
5.0
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
>>> r
0
>>> rows.index(r)
2The loop variable r shows which value caused the error. You didn't have to add debugging prints and rerun the script.
Setting up every session with PYTHONSTARTUP
-i is for one script. If you want the same imports every time you open a plain python3 shell, use the PYTHONSTARTUP environment variable. Set it to the path of a Python file. Python runs that file before the first prompt of an interactive session, in the same namespace as your typing.
Create ~/.pythonrc.py:
import math
import os
import sys
from pathlib import Path
print("startup file loaded")On Linux or macOS, set the variable in your shell profile:
export PYTHONSTARTUP="$HOME/.pythonrc.py"On Windows, setx stores it for future terminals. Open a new terminal afterwards.
setx PYTHONSTARTUP "%USERPROFILE%\.pythonrc.py"Now a new session starts with math, os, sys, and Path ready:
startup file loaded
>>> math.sqrt(16)
4.0
>>> Path.home().name != ""
TrueRules and gotchas
- Python reads the startup file only for interactive sessions. A script run as
python3 script.pydoes not execute it, so never make a script depend on it. - Code that relies on names from the startup file works in your shell but fails in a teammate's. Keep that code out of anything you share.
- Keep the file short. Everything in it runs on every launch, and a slow import delays every session.
- An error in the startup file prints a traceback, so check the file after you edit it.
Choosing between the two
| Need | Use |
|---|---|
| Explore the results of one specific script | `python3 -i script.py` |
| Inspect variables after a crash | `python3 -i script.py` |
| Have the same helpers in every shell | `PYTHONSTARTUP` |
Exercise
You run python3 -i report.py, and the script stops with an uncaught KeyError. Does the >>> prompt appear, and can you still read the variables the script had set before the error?
Show answer
Yes to both. With -i, Python prints the traceback and then opens the prompt. The script's variables and functions from before the error are still defined, so you can inspect them.
Exercise
You put import math in your PYTHONSTARTUP file. A script that you run with python3 tool.py calls math.sqrt(2) without its own import. What happens, and why?
Show answer
The script fails with a NameError, because PYTHONSTARTUP is read only for interactive sessions. The script must contain import math itself.