2

Is it possible to perform an action when a top level python package is called from the command line?

For example, my current structure looks like this:

MyApp 
    | - subdir1 
        | - pyfile.py
        | - pyfile.py
        | - pyfile.py
    | - subdir2
        | - subsubdir1
            | - pyfile.py
            | - pyfile.py
    - __init__ 
    - other.py 

And I can do all the normal stuff. e.g. from MyApp.subdir1 import pyfile.

However, I'd like to allow users to call the app via its top level name from command line and have it do something

python MyApp [options]

Rather than them having to scope it to a specific module with a main() func

python /path/to/MyApp/actions/somemodule.py [options]

Is this at all possible?

user3308774
  • 1,354
  • 4
  • 16
  • 20

1 Answers1

4

Try python -m MyApp [options], where your __init__.py contains a if __name__ == "__main__": block.

If you want to make that even easier for users, make it so that your setup.py script installs a command (e.g. /usr/bin/MyApp) that just contains the following:

#!/bin/bash
python -m MyApp $@

That way, they don't even have to know it's a Python program. All they have to do is call MyApp [options].

Setuptools can even generate that automatically, it's called an "entry point". See this question for more details on how they work: Explain Python entry points?

Community
  • 1
  • 1
Max Noel
  • 8,810
  • 1
  • 27
  • 35