Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

Answer from Ned Batchelder on Stack Overflow
Top answer
1 of 6
514

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

2 of 6
215

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
└── demo
    ├── __init__.py
    └── __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

🌐
Python
docs.python.org › 3 › library › __main__.html
__main__ — Top-level code environment — Python 3.14.6 ...
Code within this block won’t run unless the module is executed in the top-level environment. Putting as few statements as possible in the block below if __name__ == '__main__' can improve code clarity and correctness. Most often, a function named main encapsulates the program’s primary behavior: # echo.py import shlex import sys def echo(phrase: str) -> None: """A dummy wrapper around print.""" # for demonstration purposes, you can imagine that there is some # valuable and reusable logic inside this function print(phrase) def main() -> int: """Echo the input arguments to standard output""" phrase = shlex.join(sys.argv) echo(phrase) return 0 if __name__ == '__main__': sys.exit(main()) # next section explains the use of sys.exit
Discussions

How to run a Python script from the main script?
Create some functions like “run()” in detect and code. Create a new file called “main.py” and import “run()” from detect and code. Call “detect.run()” and “code.run()” That should do it 👍 More on reddit.com
🌐 r/learnpython
20
31
December 27, 2022
How to run main.py?
Open up cmd and type: pip install tkinker Or pip3, depending what you use. Btw this is a subreddit for the ide and not to fix someones code, go to r/python or something. More on reddit.com
🌐 r/vscode
10
0
June 5, 2024
Python IDLE: Run main? - Stack Overflow
There is really no such concept of "main" as e.g. in Java. As Python is interpreted, all lines of code are read and executed when importing/running the module. Python provides the __name__ mechanism for you to distinguish the import case from the case when you run your module as a script i.e. python mymodule.py... More on stackoverflow.com
🌐 stackoverflow.com
what is the simplest way to run a a python script?
I would be very careful before letting code, produced by Chatgpt, play with my file system. More on reddit.com
🌐 r/learnpython
19
8
February 13, 2023
🌐
Real Python
realpython.com › run-python-scripts
How to Run Your Python Scripts and Code – Real Python
February 25, 2026 - Running Python scripts is essential for executing your code. You can run Python scripts from the command line using python script.py, directly by making files executable with shebangs on Unix systems, or through IDEs and code editors.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-main-function
How to Use the Python Main Function | DigitalOcean
March 19, 2026 - Python finds that module and executes it as a script, setting __name__ to "__main__" inside that module. So the same file can behave as either the main program or a library depending on Python import vs direct execution. The following example demonstrates both paths with annotated output.
🌐
Reddit
reddit.com › r/learnpython › how to run a python script from the main script?
r/learnpython on Reddit: How to run a Python script from the main script?
December 27, 2022 -

I'm currently working on a project to detect tools in a box using Yolov7, OpenCV etc. on my Jetson Nano, and one of the features is to see the dot matrix digits on the weighing scale in the box to convert it into a string which will send it into a database.

Right now I have the main script that detects the tools called detect.py and I have made a separate script to see the digits called code.py. But the problem I'm facing now is I'm struggling to integrate both codes together and I wonder if there is a way for me to run code.py once I run detect.py so they both run at the same time.

Would appreciate the assistance. Sorry if the description is too vague!

🌐
GeeksforGeeks
geeksforgeeks.org › python › usage-of-__main__-py-in-python
Usage of __main__.py in Python - GeeksforGeeks
April 28, 2025 - Now when we run them from terminal/command prompt like this ... The output will be - So what happens when we execute the command. Python looks for a file named __main__.py to start its execution automatically.
🌐
Oreate AI
oreateai.com › blog › how-to-run-python-main-py › 9025d55130ed6355d01d63cad4b77f96
How to Run Python Main Py - Oreate AI Blog
January 7, 2026 - Use interactive mode by simply ... running a simple script like main.py boils down to navigating via command line and invoking python followed by your filename—easy peasy!...
Find elsewhere
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python main function and examples with code
Python Main Function and Examples with Code
May 31, 2023 - In Python, the role of the main() function is to act as the starting point of execution for any software program. The execution of the program starts only when the main() function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.
🌐
Real Python
realpython.com › python-main-function
Defining Main Functions in Python – Real Python
December 21, 2023 - Most often, you will see this recommended when you’re using pip: python3 -m pip install package_name. Adding the -m argument runs the code in the __main__.py module of a package.
🌐
Medium
medium.com › @jameskabbes › adding-main-py-to-your-python-package-ff0cba4b8f98
Adding __main__.py to your Python package | by James Kabbes | Medium
September 21, 2023 - To call the package as “main”, run “python -m file_counter” from terminal. ... Some Python packages benefit from having __main__.py.
🌐
GitHub
gist.github.com › rochacbruno › ed19c5d9ba9bb50391a2
Use of __main__.py · GitHub
Save rochacbruno/ed19c5d9ba9bb50391a2 to your computer and use it in GitHub Desktop. ... it can also work in submodules if you have a subfolder just use the dot python myprojectfolder.subfolder and the __main__.py inside that folder will be executed · Python will execute the code in __main__.py as this file is an entry point. ... YES Python can Zip files and folders! and now you can get rid of myprojectfolder source code and run...
🌐
Reddit
reddit.com › r/vscode › how to run main.py?
r/vscode on Reddit: How to run main.py?
June 5, 2024 -

I'm doing a course on Python. I have a main.py file. If I open the parent folder and try to run the file, it doesn't work. Why's that?

I get an error like this "ImportError: No module named tkinter"

I'm sure there's a basic fundamental I'm not understanding.

Thanks.

🌐
Hrekov
hrekov.com › blog › the-main-py-file
The `__main__.py` File: The Front Door to Your Python Package | Web Tools, Production APIs & Technical Blog | Hrekov
April 2, 2026 - from .logic import start_engine def main(): print("Initializing Application...") start_engine() if __name__ == "__main__": main() How to run it: From the parent directory, you simply type: ... It's easy to get these two confused.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-run-a-python-script
How to Run a Python Script - GeeksforGeeks
To run a Python script in Terminal from the command line, navigate to the script's directory and use the python script_name.py command. Redirecting output involves using the > symbol followed by a file name to capture the script's output in a file.
Published   October 2, 2025
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-main.html
Python main() - Command Line Arguments
Command line arguments like -affirm often select a mode or option for the run of the program, and these options typically begin with a dash as we have here. With the -hello option, the program prints a plain hello like this: ... With the -n option, the program prints the name a number of times, like this. $ python3 affirm.py -n 10 Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie $ python3 affirm.py -n 100 Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Maggie Ma
🌐
Python Morsels
pythonmorsels.com › making-main-function-python
Defining a main function in Python - Python Morsels
September 27, 2021 - This version of our greet.py file can be run as a program to print out a random greeting: ... But if we import it as a module, it doesn't do anything (except give us access to functions and whatever else is in that module): ... It turns out there's a way to ask, are we being run from the command-line. Or put another way, is our current Python module the entry point to our Python process? This question can be asked using the statement __name__ == "__main...
🌐
Edureka
edureka.co › blog › python-main-function
What is the Main Function in Python and how to use it | Edureka
November 27, 2024 - So, if you are running the script directly, Python is going to assign “__main__” to __name__, i.e., __name__= “__main__”. (This happens in the background). As a result, you end up writing the conditional if statement as follows: ... Hence, if the conditional statement evaluates to True, it means, the .py (Python Script) file is being run or executed directly.
🌐
Reddit
reddit.com › r/learnpython › what is the simplest way to run a a python script?
r/learnpython on Reddit: what is the simplest way to run a a python script?
February 13, 2023 -

i have this script that chatgpt made for me, i want to test it out but i am new to coding and im not sure how to run it.
i tried googling it but many of them go into way to deep detail and have just walls of text that for someone with dyslexia is very hard to read. i have python and pip installed and they are up to date along with notepad++

import os

def rename_files_in_folder(folder_path, prefix, exclude_filename=None):
    # Get a list of all files in the folder
    files = os.listdir(folder_path)

    # Rename each file with a prefix and number, excluding the specified file
    for i, filename in enumerate(files):
        if filename == exclude_filename:
            continue
        new_filename = f"{prefix}{i + 1}{os.path.splitext(filename)[1]}"
        os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))

# Example usage
rename_files_in_folder("/path/to/folder", "new_file_", exclude_filename="file_to_exclude.txt")
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-main-function
Python Main Function - GeeksforGeeks
August 9, 2024 - File1 __name__ = File1 File1 is being imported File2 __name__ = __main__ File2 is being run directly · As seen above, when File1.py is run directly, the interpreter sets the ... and when it is run through File2.py by importing, the __name__ variable is set as the name of the python script, i.e.