[英]Python package distribution with entry_point console_script
I am preparing to deploy a Python package with the following layout:我正准备部署一个 Python package 布局如下:
MyPackage/
setup.py
MyPackage/
__init__.py
__main__.py
lib/
__init__.py
utils.py
db/
__init__.py
db1.py
db2.py
tasks/
__init__.py
something.py
The setup.py
contains: setup.py
包含:
setup(name = MyPackage,
...
packages = find_packages(),
include_package_data = True,
entry_points = {"console_scripts" : [
"do_something = MyPackage.__main__:main"
]})
__main__.py
contains: __main__.py
包含:
import tasks.something as something
something.my_function()
something
module contains: something
模块包含:
import db.db1 as db1
import db.db2 as db2
def my_function():
db1.this_func(...)
db2.that_func(...)
db1
contains: db1
包含:
import sqlalchemy
import lib.utils as utils
def this_func(...):
sqlalchemy.create_engine(...)
and db2
contains: db2
包含:
import sqlalchemy
import lib.utils as utils
def that_func(...):
sqlalchemy.create_engine(...)
When run by executing from the installed site-packages
directory, __main__.py
completes without issue.通过从安装的
site-packages
目录执行运行时, __main__.py
完成没有问题。 If I perform import MyPackage.tasks.something as something
in an interactive session, the module also imports with issue.如果我在交互式 session 中执行
import MyPackage.tasks.something as something
,则该模块也会导入问题。 When I run the console_scripts
script do_something
, however, I receive ModuleNotFound
errors for tasks
.但是,当我运行
console_scripts
脚本do_something
时,我收到了针对tasks
的ModuleNotFound
错误。
What is causing my console script to fail to locate the subpackages?是什么导致我的控制台脚本无法找到子包?
Thanks in advance!提前致谢!
Change your imports, following this example:按照以下示例更改您的导入:
__main__.py : __main__.py :
import tasks.something as something
# to:
import MyPackage.tasks.something as something
# or
from .tasks import something as something
Two problems here.这里有两个问题。
__main__.py
were implicit relative. __main__.py
中的导入语句是隐式相对的。 Change them to absolute imports.console_scripts
entry point target needs to resolve to a callable which accepts no arguments . console_scripts
入口点目标需要解析为不接受 arguments的可调用对象。 In your case, that means the module MyPackage/__main__.py
should define a callable main
.MyPackage/__main__.py
应该定义一个可调用的main
。 Change __main__.py
like this:像这样更改
__main__.py
:
from MyPackage.tasks import something
def main():
# command line arguments parsing and logging configuration goes here ..
something.my_function()
if __name__ == "__main__":
main()
Similarly, you should change the import statements in db1
, db2
, and something
into correct relative imports:同样,您
something
将db1
、 db2
中的导入语句更改为正确的相对导入:
from ..db import db1
from ..db import db2
from ..lib import utils
Alternatively, use absolute imports:或者,使用绝对导入:
from MyPackage.db import db1
from MyPackage.db import db2
from MyPackage.lib import utils
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.