Python
File Execution
Python Interpreter
Programming Tutorial
Python Scripting

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.

Browse interview questions

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.

python
exec(open('helpers.py', encoding='utf-8').read())

This reads the file and executes its contents in the current namespace. Functions, classes, and variables defined in the file become immediately available.

python
>>> exec(open('helpers.py', encoding='utf-8').read())
>>> result = my_function(42)
>>> print(result)

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.

python
import my_script
print(my_script.MY_CONSTANT)
print(my_script.my_function(42))

If you edit the file and want to re-run it in the same interpreter, use importlib.reload.

python
1import importlib
2import my_script
3
4importlib.reload(my_script)

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.

python
1import runpy
2
3namespace = runpy.run_path('my_script.py')
4print(namespace.keys())

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.

python
1import subprocess
2
3result = subprocess.run(
4    ['python3', 'my_script.py'],
5    capture_output=True,
6    text=True,
7    check=False,
8)
9
10print(result.stdout)
11print(result.stderr)

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.

python
1import sys
2
3sys.argv = ['my_script.py', '--input', 'data.csv']
4exec(open('my_script.py', encoding='utf-8').read())

With subprocess, argument passing is more natural.

python
import subprocess

subprocess.run(['python3', 'my_script.py', '--input', 'data.csv'])

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 exec for quick one-off interactive loading
  • use import when the file is really a module
  • use runpy when you want script-style behavior inside Python
  • use subprocess when 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.'
  • 'import is 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.