How to execute a file within the Python interpreter?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Running a Python file from inside the interpreter can mean several different things: executing its code in the current namespace, importing it as a module, or running it in an isolated process. The right approach depends on whether you want to reuse definitions interactively, trigger __main__ behavior, or avoid changing the current interpreter state.
Use exec for Simple Interactive Loading
If you want to execute a file directly into the current interpreter session, exec is the simplest tool.
This reads the file and executes its contents in the current namespace. Functions, classes, and variables defined in the file become immediately available.
This is convenient for ad hoc exploration, but it is also the least structured approach because it can overwrite names in your current session.
Import the File as a Module When Possible
If the file is a real Python module, importing it is usually cleaner.
If you edit the file and want to re-run it in the same interpreter, use importlib.reload.
This keeps the code inside a module namespace instead of splashing every symbol into the interactive environment.
Use runpy to Emulate Script Execution
If you want behavior closer to running python my_script.py, use runpy.run_path.
This executes the file as a script-like unit and returns the resulting namespace as a dictionary. It is useful when you want to trigger if __name__ == '__main__': style behavior without starting a separate process manually.
Use subprocess for Isolation
If the script should run independently and should not modify the current interpreter state, use subprocess.
This is the safest pattern when the script has side effects, uses command-line arguments, or should behave exactly as it would from the shell.
Pass Arguments Deliberately
Some scripts depend on sys.argv. If you run them with exec, you may need to set that state yourself.
With subprocess, argument passing is more natural.
If the script is designed to be a CLI program, subprocess is usually the more honest execution model.
Choose Based on the Goal
A practical rule of thumb is:
- use
execfor quick one-off interactive loading - use
importwhen the file is really a module - use
runpywhen you want script-style behavior inside Python - use
subprocesswhen isolation matters
That keeps the execution style aligned with the reason you are running the file.
Common Pitfalls
A common mistake is using exec on code you do not fully trust. It executes with full access to the current interpreter state.
Another is expecting import to re-run the file automatically after edits. Python caches imported modules, so you need importlib.reload if you want to execute the module again.
Developers also forget that running a script inside the interpreter and running it as a separate process are different behaviors. The choice affects __name__, global state, and path handling.
Summary
- '
exec(...)runs a file in the current interpreter namespace.' - '
importis cleaner when the file is really a module.' - '
runpy.run_path(...)gives script-like execution without leaving Python.' - '
subprocess.run(...)is best when you want isolation.' - Pick the method that matches whether you want reuse, script semantics, or process separation.
Related reading
- How to execute a function asynchronously every 60 seconds in Python?
- How to execute a Python script from the Django shell?
- How to execute multi-line statements within Python's own debugger PDB
- How to execute Python code from within Visual Studio Code
- How to execute raw SQL in Flask-SQLAlchemy app
- How to exit from Python without traceback?
- How to exit the entire application from a Python thread?
- How to expand a list to function arguments in Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.