Profile photo for Fred Cirera

Create self contained python executables.


Every one knows the special file "__init__.py". There is another special file "__main__.py". If this file exists in a directory, the python interpreter will try to execute it.

Here is an example:

  1. #fred:$ find . 
  2. . 
  3. ./hello 
  4. ./hello/__main__.py 

In our example the content of the file is a simple loop that prints hello world.

  1. #fred:$ cat ./hello/__main__.py 
  2. # 
  3. for count in range(3): 
  4. print 'hello (cruel) world' 

Just call python with the directory name and the python interpreter will execute the file __main__.py

  1. #fred:$ python hello 
  2. hello (cruel) world 
  3. hello (cruel) world 
  4. hello (cruel) world 

Now the interesting part...

Python is capable of importing and executing whatever python code is in a zip file. Therefore we can do the following:

  1. #fred:$ (cd hello; zip -r ../hello.zip .) 
  2. adding: __main__.py (stored 0%) 
  3.  
  4. #fred:$ python hello.zip 
  5. hello (cruel) world 
  6. hello (cruel) world 
  7. hello (cruel) world 

On any Unix like system we can use a shebang (#!) line at the beginning of a file to pass the content of that file to the interpreter specified after the shebang.

  1. #fred:$ echo '#!/usr/bin/env python' > greetings 
  2. #fred:$ cat hello.zip >> greetings 
  3. #fred:$ chmod a+x greetings 

We can now execute that file.

  1. #fred:$ ./greetings 
  2. hello (cruel) world 
  3. hello (cruel) world 
  4. hello (cruel) world 

Mix that with virtualenv and you will have a powerful way to simply distribute and execute your code.

View 100+ other answers to this question
About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025