[英]Making a top level python module callable?
Is it possible to perform an action when a top level python package is called from the command line? 从命令行调用顶级python 包时是否可以执行操作?
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
. 例如
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 而不是必须使用
main()
函数将其范围限定到特定模块
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. 尝试使用
python -m MyApp [options]
,其中__init__.py
包含if __name__ == "__main__":
块。
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: 如果您想让用户更轻松地进行操作,请执行以下操作,以便
setup.py
脚本安装仅包含以下内容的命令(例如/usr/bin/MyApp
):
#!/bin/bash
python -m MyApp $@
That way, they don't even have to know it's a Python program. 这样,他们甚至不必知道这是一个Python程序。 All they have to do is call
MyApp [options]
. 他们所要做的就是调用
MyApp [options]
。
Setuptools can even generate that automatically, it's called an "entry point". Setuptools甚至可以自动生成该文件,称为“入口点”。 See this question for more details on how they work: Explain Python entry points?
有关其工作方式的更多详细信息,请参见此问题: 解释Python入口点?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.