Python __main__.py: How to Run a Folder Like a Script

Introduction

Most Python developers know how to run a script:

python myscript.py

But here’s something you might not know — Python can also run an entire folder.
The secret? A special file called __main__.py.

When present in a package, __main__.py tells Python:

“If someone runs this folder, start execution here.”

This makes it perfect for command-line tools, project entry points, and even runnable .zip files.


What is __main__.py?

  • A special Python file inside a package
  • Serves as the entry point when the package is run directly
  • Similar to the if __name__ == "__main__": block in scripts
  • Can be used in folders or .zip archives

Basic Example

Folder structure:

mypackage/
__main__.py
helper.py

Inside __main__.py:

print("Hello from __main__.py!")

Run the package:

python mypackage/

Output:

Hello from __main__.py!

Why Is It Useful?

  1. Cleaner Project Structure
    • Keep your code split across modules but still have one easy entry point.
  2. Command-Line Tools
    • Turn your package into a CLI app without a separate runner script.
  3. Runnable .zip Files
    • Package your code, compress it, and still run it directly:
    • python myapp.zip
  4. Reusable for Multiple Entry Points
    • Combine with argparse to handle CLI commands from within a package.

Advanced Example — CLI Tool

Structure:

todo_app/
__main__.py
tasks.py

__main__.py:

import sys
from tasks import list_tasks, add_task

if len(sys.argv) < 2:
print("Usage: python todo_app [list|add] [task]")
elif sys.argv[1] == "list":
list_tasks()
elif sys.argv[1] == "add":
add_task(sys.argv[2])

tasks.py:

tasks = []

def list_tasks():
print("Tasks:", tasks)

def add_task(task):
tasks.append(task)
print(f"Added task: {task}")

Run:

python todo_app add "Learn Python"
python todo_app list

Using __main__.py in Zip Apps

You can even run zipped packages:

Structure:

myapp.zip/
__main__.py
module.py

Run it:

python myapp.zip

Best Practices

✅ Keep __main__.py minimal — delegate real work to other modules
✅ Use it for CLI entry points (argparse works perfectly here)
✅ Works well with if __name__ == "__main__": for scripts
❌ Avoid heavy startup logic — keep imports light for faster execution


Recap

  • __main__.py lets you run a folder or .zip file like a script
  • Ideal for CLI apps, project entry points, and distributable tools
  • Keeps code organized while still being easy to execute

Related Reads in This Series:

  1. Python __pycache__ Explained — Must-Have Guide for Beginners
  2. Python .pth Files — How Python Secretly Includes Extra Folders in Your Import Path
  3. Python __init__.py — The File That Turns a Folder into a Package

Leave a Reply

Your email address will not be published. Required fields are marked *