Sub topic 12
Dropping into the shell after a script with python -i and PYTHONSTARTUP
This chapter assumes you can start the interactive shell, read a traceback, and import modules. It also assumes you can set an environment variable in your terminal. You will learn two ways to combine scripts with the shell. python -i runs a script and then leaves you at the prompt. PYTHONSTARTUP runs a file of your own each time a plain interactive session starts.
Why combine a script with the shell
A script runs top to bottom and exits. Its variables are gone as soon as the process ends. That is awkward when you want to ask a follow-up question about its results, or find out why it failed.
The shell has the opposite problem. It is good for follow-up questions, but retyping setup code is tedious. Two features cover the gap:
python -i script.pyruns the script first, then gives you a prompt in the same process. The script's names are still defined.PYTHONSTARTUPnames a file that Python runs before the first prompt of every plain interactive session. It is a personal setup file.
Running a script with python -i
Take this script, saved as shop.py:
prices = {"apple": 0.5, "pear": 0.75, "plum": 0.4}
def total(names):
return sum(prices[n] for n in names)
print("loaded", len(prices), "prices")Run it with the -i option:
python3 -i shop.pyThe script runs, prints its output, and then the >>> prompt appears. Everything the script defined lives in the session's __main__ namespace:
loaded 3 prices
>>> total(["apple", "pear"])
1.25
>>> prices["plum"] = 0.45
>>> total(["plum"])
0.45
>>> sorted(prices)
['apple', 'pear', 'plum']You can call the script's functions with new arguments, change its data, and check intermediate values. The edits exist only in this session. The file on disk is unchanged.
Option order matters
Python reads its own options before the script name. Anything after the script name goes to the script through sys.argv.
python3 -i shop.py --verbose # -i is Python's; --verbose goes to the script
python3 shop.py -i # wrong: -i goes to the script, no shell appearsThe same rule applies to -m and -c. python3 -i -m mypackage.tool and python3 -i -c "x = 42" both end at a prompt.
The __main__ guard still runs
When you start a script with python -i script.py, its __name__ is "__main__". An if __name__ == "__main__": block therefore runs, including any call to a main() function. Setup code you want to inspect afterward should either sit at module level or be reachable from the guard.
def main():
global rows
rows = [n * n for n in range(5)]
print("computed", len(rows), "rows")
if __name__ == "__main__":
main()The global rows line is the point of this example. Without it, rows would be a local variable of main(). The function would end, the name would vanish, and rows would not exist at the prompt. Values you want to inspect must be globals, or main() must return them so you can call it again at the prompt.
Inspecting a failed script
Running a failing script under -i is the main reason to learn this option. Python still enters interactive mode after an uncaught exception. The script's state at the moment of failure is available to you.
Save this as fail.py:
values = [3, 1, 0]
results = []
for v in values:
results.append(10 / v)Run it:
python3 -i fail.pyTraceback (most recent call last):
File "fail.py", line 4, in <module>
results.append(10 / v)
ZeroDivisionError: division by zero
>>> v
0
>>> results
[3.3333333333333335, 10.0]
>>> values.index(v)
2The traceback appears first. The exact file path and the marker lines under the code vary between Python versions. The prompt then lets you see that v was 0 and that two results were stored before the failure.
For a deeper look, use the debugger's post-mortem mode. After an uncaught exception, Python records the traceback in sys.last_traceback. pdb.pm() opens the debugger at the frame that failed:
>>> import pdb
>>> pdb.pm()At the (Pdb) prompt you can print variables and move up and down the call stack. Type q to leave the debugger and return to the >>> prompt.
Other ways to request the same behavior
The environment variable PYTHONINSPECT has the same effect as -i. Set it to any non-empty string. A script can also set it for itself, by assigning to os.environ["PYTHONINSPECT"] before it exits. That is a quick way to make one script always end in a shell during debugging.
PYTHONINSPECT=1 python3 shop.pyRemove it when you are done. A script that waits for input at exit hangs in scheduled jobs and other places where nobody is at a terminal.
Startup files with PYTHONSTARTUP
PYTHONSTARTUP holds the path of a Python file. Python runs that file once, before showing the first prompt of an interactive session. The file runs in the same namespace as your commands, so names it defines are available right away.
Create a file such as ~/.pythonrc.py:
import json
import os
import sys
from pathlib import Path
from pprint import pprint
print(f"Python {sys.version.split()[0]} with json, os, sys, Path and pprint loaded")Point the variable at it. On Linux or macOS with bash or zsh:
export PYTHONSTARTUP="$HOME/.pythonrc.py"
python3On Windows Command Prompt, use set PYTHONSTARTUP=%USERPROFILE%\.pythonrc.py. To keep the setting, add the line to your shell profile on Linux or macOS. On Windows, add it to the user environment variables.
In the session, the imported names are already there:
Python 3.12.4 with json, os, sys, Path and pprint loaded
>>> Path.cwd().name
'work'
>>> pprint(sorted(os.environ)[:3])
['HOME', 'LANG', 'PATH']The version number and the printed values are examples from one machine. Yours will differ.
What a startup file should and should not do
Good uses:
- Imports you type in nearly every session.
- Small helper functions for your own habits, such as a function that prints a dictionary in sorted order.
- Settings for line editing or history, if your Python build supports them.
Poor uses:
- Anything slow, such as heavy imports or network calls. The delay appears on every session.
- Code that changes behavior in ways you will forget. A tutorial example that works for you may fail for a colleague who lacks your startup file.
- Code you want other people to run. A startup file is local to your machine and is not part of your project.
Imports in the startup file also clutter dir(). If helper variables should not stay in the namespace, delete them at the end of the file with del.
The two features do not combine
Python's documentation states this for -i: "The PYTHONSTARTUP file is not read." When you run python3 -i shop.py, the startup file is skipped. Only a plain interactive session with no script reads it. This surprises people who put imports in a startup file and then wonder why the names are missing after python -i script.py.
If you want both, import the startup file yourself from the script, or run it by hand at the prompt:
>>> import os
>>> exec(open(os.environ["PYTHONSTARTUP"]).read())Also, PYTHONSTARTUP applies only to interactive sessions. A script run with python3 shop.py never reads it, so your scripts do not depend on it by accident.
Comparing the ways to start
| Command | Script runs | Startup file read | Ends at prompt |
|---|---|---|---|
| `python3` | No | Yes, if set | Yes |
| `python3 script.py` | Yes | No | No |
| `python3 -i script.py` | Yes | No | Yes, even after an exception |
| `PYTHONINSPECT=1 python3 script.py` | Yes | No | Yes |
Common mistakes
- Putting
-iafter the script name. The script receives it as an ordinary argument and no prompt appears. - Expecting local variables to survive. Only module-level names remain. Names inside a finished function are gone.
- Expecting the startup file under
-i. It is not read. See the section above. - Editing the script and expecting the session to update. The session keeps the old definitions. Use
importlib.reload()for modules you imported, or exit and start again for the main script. For a script you started with-i, restarting is simpler, because its code lives in__main__and cannot be reloaded. - Leaving
PYTHONINSPECTset. Automated runs then wait for input forever.
Exercises
Exercise
You run python3 -i report.py. The script finishes, but at the prompt total is not defined, although report.py assigns total = sum(rows) inside def main():. Why, and what are two ways to fix it?
Show answer
The assignment is local to main(), so the name disappears when the function returns. Either declare global total inside main(), or make main() return the value and call it at the prompt (total = main()). Moving the assignment to module level also works.
Exercise
You put import json in the file named by PYTHONSTARTUP. Does json exist after python3 and after python3 -i script.py?
Show answer
After plain python3, yes, because the startup file runs before the first prompt. After python3 -i script.py, no, unless the script imports it. Python does not read PYTHONSTARTUP when you pass a script, even with -i.
Exercise
A script crashes with an uncaught KeyError partway through. What command starts it so you land at a prompt with the failing state intact, and which two lines open the debugger at the failed frame?
Show answer
Run python3 -i script.py. At the prompt, type import pdb and then pdb.pm().