Skip to content

Instantly share code, notes, and snippets.

@chespinoza
Forked from rochacbruno/mainpython.md
Created May 6, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chespinoza/6b0a82d86db6ad8b73d3e51b4e258d21 to your computer and use it in GitHub Desktop.
Save chespinoza/6b0a82d86db6ad8b73d3e51b4e258d21 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

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__.py 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

YES Python can Zip files and folders!

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

python myproject.zip

YES! Python can execute zipped files (remember the .egg)

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

./myprogram

Sometimes it is better than the hackkish if __name__ == "__main__"

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

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