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. eg 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?
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 (eg /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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.