Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to execute a Python file in Python shell?
When working with Python, you often need to execute Python files from within the Python shell or interactive environment. This allows you to test scripts, debug code, and interact with functions without leaving your current Python session.
Using exec() Function
The most common method is using the exec() function to read and execute a Python file ?
Example
First, create a simple Python file called hello.py ?
# hello.py
print("Hello from the script!")
name = "Python"
print(f"Welcome to {name} programming!")
Now execute it from the Python shell ?
with open("hello.py", "r") as file:
script_content = file.read()
exec(script_content)
Hello from the script! Welcome to Python programming!
Using %run Magic Command in IPython
If you're using IPython or Jupyter, the %run magic command provides a convenient way to execute Python files ?
Example
%run hello.py
Hello from the script! Welcome to Python programming!
The %run command executes the file in the current namespace, making all variables and functions available for interaction.
Using subprocess Module
You can execute a Python file as a separate process using the subprocess module ?
Example
import subprocess result = subprocess.run(["python", "hello.py"], capture_output=True, text=True) print(result.stdout)
Hello from the script! Welcome to Python programming!
Using importlib Module
For dynamic loading and execution, use the importlib module ?
Example
import importlib.util file_path = "hello.py" module_name = "hello_module" spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module)
Hello from the script! Welcome to Python programming!
Comparison of Methods
| Method | Best For | Namespace | Error Handling |
|---|---|---|---|
exec() |
Simple execution | Current namespace | Direct exceptions |
%run |
IPython/Jupyter | Current namespace | IPython features |
subprocess |
Isolated execution | Separate process | Return codes |
importlib |
Dynamic loading | Module namespace | Import-like behavior |
Key Points
? Use exec() for simple file execution within the current namespace
? Use %run in IPython/Jupyter environments for interactive development
? Use subprocess when you need isolated execution or want to capture output
? Use importlib for dynamic module loading with proper namespace management
Conclusion
Each method serves different purposes: exec() for simple execution, %run for interactive development, subprocess for isolated processes, and importlib for dynamic loading. Choose the method that best fits your specific use case and environment.
