Course contentsShow
← Python
Lesson 179 of 1,0603. Functions and ModularizationFree lesson

Distributing Code with Entry Points and Scripts

Learners will configure their project structure to allow modules to be executed as standalone command-line tools using the -m flag.

In this lesson, you will learn how to configure your project structure so your Python modules can be executed as standalone command-line tools using the -m flag.

The Problem with Direct Execution

When you organize your code into packages and sub-modules, simply running python my_script.py often leads to ImportError issues because the Python interpreter struggles to resolve relative imports when it doesn't recognize the directory structure as a proper package. To solve this, Python provides the -m (module) flag, which treats a module as a top-level script while maintaining your package’s internal structure.

Using the if __name__ == "__main__": Guard

To make a module "runnable," you must include the main guard we discussed previously. This ensures that the code inside the block only executes when you call the file directly, but remains silent when you import that file into another part of your project.

Imagine a file structure like this:

my_project/
├── my_package/
│   ├── __init__.py
│   └── calculator.py

Inside calculator.py, you define your logic:

def add(a, b):
    return a + b

if __name__ == "__main__":
    import sys
    # A simple command-line interface
    args = sys.argv[1:]
    print(add(int(args[0]), int(args[1])))

Running with the -m Flag

Once your main guard is in place, you don't need to navigate into the folder and run the file directly. Instead, from the parent directory of my_project, you can run the module using the dot-notation path:

python -m my_package.calculator 5 10

The -m flag tells Python to locate the module my_package.calculator within your environment's path and execute its contents. Because you wrapped the execution logic in the if __name__ == "__main__": block, Python treats the module as a script only when triggered this way. This allows you to distribute your code so that users can interact with your modules directly from their terminal without needing to write their own wrapper scripts.

Key Takeaway: By using the if __name__ == "__main__": guard combined with the python -m flag, you turn your modular Python files into professional command-line tools that respect your project’s internal structure.