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

Pavol Kutaj
2 min readJan 26, 2022

--

1. NOTES

  • 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 __main__.py
  • for example, my python app is located in the support-kb folder
  • without __main__.py, 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 __main__.py 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 __main__.py will get executed
~\Documents\support-kb ▶ echo "print('executing __main.py__ of support-kb')" > __main__.py
~\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, __main__.py 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

2. CONSEQUENCES/CONSTRAINTS

  • 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 __main__.py by appending "" to sys.path and change the CWD to the name of the actual directory
# __main.py__
sys.path.append("")
os.chdir("./support-kb")

3. EXAMPLE

4. LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com

Recommended from Medium

Lists

See more recommendations