You've not called your main function at all, so the Python interpreter won't call it for you.
Add this as the last line to just have it called at all times:
main()
Or, if you use the commonly seen:
if __name__ == "__main__":
main()
It will make sure your main method is called only if that module is executed as the starting code by the Python interpreter. More about that here: What does if __name__ == "__main__": do?
If you want to know how to write a 'main' function, Guido van Rossum (the creator of Python) wrote about it in 2003.
Answer from user764357 on Stack OverflowYou've not called your main function at all, so the Python interpreter won't call it for you.
Add this as the last line to just have it called at all times:
main()
Or, if you use the commonly seen:
if __name__ == "__main__":
main()
It will make sure your main method is called only if that module is executed as the starting code by the Python interpreter. More about that here: What does if __name__ == "__main__": do?
If you want to know how to write a 'main' function, Guido van Rossum (the creator of Python) wrote about it in 2003.
Python isn't like other languages where it automatically calls the main() function. All you have done is defined your function.
You have to manually call your main function:
main()
Also, you may commonly see this in some code:
if __name__ == '__main__':
main()
Well, I'm trying to figure out what is the best way to write one-file Python programs in terms of structure.
For the purpose of this post I will focus only in the use of the main() function.
Most people out there will write their one-file program this way:
# ...imports, globals, constats...
def first_thing_to_do():
do stuff
def second_thing_to_do()
do more stuff
def main():
first_thing_to_do()
second_thing_to_do()
if __name__ == "__main__":
main()But I think the more logical and readable order for a human is:
# ...imports, globals, constats...
def main():
first_thing_to_do()
second_thing_to_do()
def first_thing_to_do():
do stuff
def second_thing_to_do()
do more stuff
if __name__ == "__main__":
main()In the second way, a programmer that reads the Python program for the first time (or after some months) can see what the program does at first, and then how it does it, not the other way.
In other words, I used to write the problem definition as the main function on top (right next to imports, globals and constants), and the implementation at the bottom, as it is the most abstract (and less likely to change) part of the program.
I know Python can read it in both ways, but all the code I see on the internet use the first structure and I want to know if am I missing something or if it is just a matter of preference.
How do you write your own one-file scripts?
Hi, I just wanted someone to explain to me in a simple way what def main means in Python. I understand what defining functions means and does in Python but I never really understood define main, (but I know both def main and def functions are quite similar though). Some tutors tries to explain to me that it's about calling the function but I never understood how it even works. Any answer would be appreciated, thanks.
Hello,
I don't code Python, but I need to be able to read it in order to adapt projects to other languages.
On a CLI project, the first step is identifying the main file (the entry point).
I noticed that it's often one of the following :
-
/<name>/<name>.py -
/<name>/cli.py -
/<name>/core.py
But sometimes it's none of the above and I can only guess by name or check every file.
Is there a more reliable way ?
Thanks.
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.
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 withpython -mbut 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__.pymodule, 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.