Difference Between python3 script.py and python3 -m module: Impact on sys.path
This article explains how running a Python file directly with python3 script.py differs from using python3 -m module, focusing on the resulting changes to sys.path, import behavior, and the search order of modules.
When running a Python file directly with python3 script.py , the file is executed as a script, while using python3 -m module treats the specified module as a script, affecting how the interpreter sets up sys.path .
The first entry in sys.path differs: direct execution adds the script’s directory (or the package’s subdirectory) first, whereas module execution inserts the current working directory, ensuring relative imports work without errors.
Because sys.path mirrors the operating system’s PATH variable, it determines where the Python interpreter searches for modules. The search order includes the program’s main directory, the PYTHONPATH environment variable, standard library directories, .pth files, and various file types such as .py , .pyc , packages, and compiled extensions.
Example directory structure and code illustrate the difference:
➜ python --help
usage: /Users/escape/.pyenv/versions/MoviesList/bin/python [option] ... [-c cmd | -m mod | file | -] [args]
Options and arguments (and corresponding environment variables):
-m mod : run library module as a script (terminates option list) # Direct execution
$ python3 app/test.py
# Module execution
$ python3 -m app.test # Sample script to print sys.path
import sys
def main():
for line in sys.path:
print(line)
if __name__ == '__main__':
print(__name__)
main() # Output when run directly
__main__
/Users/escape/Fuckcode/MoviesList/lib
... (other paths) ...
# Output when run as a module
__main__
/Users/escape/Fuckcode/MoviesList
... (other paths) ...Understanding these differences helps avoid import errors and enables proper manipulation of sys.path for custom module loading.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.