How __main.py__ Can Be Used To Execute Directory With Python

Pavol Kutaj
2 min readJan 26, 2022



  • python lets you specify the main entry point which is run when a directory is executed by python
  • the main entry point must be called
  • for example, my python app is located in the support-kb folder
  • without, when I call the folder from one-folder-up
~\Documents\ ▶ python support-kb
can't find '__main__' module in 'support-kb
  • if I put the file called in the support-kb folder, python will execute it as an entry point to the app
  • you can create that file and once you call the folder, whatever is in will get executed
~\Documents\support-kb ▶ echo "print('executing __main.py__ of support-kb')" >
~\Documents\support-kb ▶ cd ..
~\Documents\ ▶ python support-kb
executing __main.py__ of support-kb
  • what happens is that a directory that is being “executed” is first added to sys.path
  • this way, can easily import any other modules with which it shares a directory
  • in this way, the directory can be conceptualized as a program
  • and this helps to organize a program in better ways:
  • use separate modules for the logically distinct parts of your program


  • there are consequences to this approach!
  • the first is that your folder name has to be compliant with module names: all-lowercase, separated exclusivelly with underscore
  • this means that support-kb is an incorrect module name and I can't use it in import statements
  • my workaround is to start the by appending "" to sys.path and change the CWD to the name of the actual directory
# __main.py__





Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at with a passion for cloud infrastructure/terraform/python/docs. More at

Recommended from Medium


See more recommendations