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

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
  • for example, my python app is located in the 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 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')" > __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
  • 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

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 is an incorrect module name and I can't use it in import statements
  • my workaround is to start the by appending to and change the CWD to the name of the actual directory
# __main.py__
sys.path.append("")
os.chdir("./support-kb")

3. EXAMPLE

4. LINKS

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com