Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Last active July 22, 2024 19:03
Show Gist options
  • Save rochacbruno/ed19c5d9ba9bb50391a2 to your computer and use it in GitHub Desktop.
Save rochacbruno/ed19c5d9ba9bb50391a2 to your computer and use it in GitHub Desktop.
Use of __main__.py

The use of __main__.py to create executables

myprojectfolder/
    |_ __main__.py
    |_ __init__.py
    |_ my_program.py

Being __main__.py:

print("Hello")

if you do

python myprojectfolder
Hello

it can also work in submodules if you have a subfolder just use the dot ``python myprojectfolder.subfolder and the main inside that folder will be executed

Python will execute the code in __main__.py as this file is an entry point.

You can also zip the folder

 python -m zipfile -c myproject.zip myprojectfolder

and now you can get rid of myprojectfolder source code and run

python myproject.zip

also you can easily obfuscate it and turn in to a binary like program

echo '#!/usr/bin/env python' >> myprogram
cat myproject.zip >>myprogram
chmod +x myprogram

Now you can delete myproject.zip and run

python myprogram

as seen on https://www.youtube.com/watch?v=0oTh1CXRaQ0

@EmbraceLife
Copy link

Great stuff! Thanks!

Copy link

ghost commented Nov 15, 2018

Hi, This may seem to be silly question. But I am curious to know why developers/programmers are not including main function in their code when they push it to a git repository? Is there any specific reason for it?

Copy link

ghost commented Jun 2, 2019

This was helpful! Thank you.

@RogerWebb
Copy link

I've run into a problem where there doesn't seem to be any way (other than manually hacking the path) to expose the other code in the module to main.py from init.py. Relative imports fail. Any tips?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment