在 setuptools 入口点上使用 importlib 动态导入库

问题描述 投票:0回答:0

我想要达到的目标

我的目标是,在安装 python 包之后,能够从未一起安装的脚本运行命令。

例子

$ excommand
Hello!

目录结构

.
├── A
    ├── __init__.py
    └── cli.py
├── .venv
├── pyproject.toml
├── setup.cfg
├── extra.py
└── extra_test.py

cli.py

import importlib

def main():
    getattr(importlib.import_module('extra'), 'hello')()

extra.py

def hello():
    print("Hello!")

extra_test.py

import importlib

getattr(importlib.import_module('extra'), 'hello')()

pyproject.toml

[build-system]
requires = [ "setuptools" ]
build-backend = "setuptools.build_meta"

设置.cfg

[metadata]
name = A
version = 1.0.0

[options]
packages = find:

[options.entry_points]
console_scripts = 
    hello = A.cli:main

问题

安装包后:

$ pip install .

命令

hello
不起作用,因为
importlib
引发错误:

$ hello
ModuleNotFoundError: No module named 'extra'

尝试了什么

我确信这与安装或 importlib 有关,因为如果我运行

python3 extra_test.py
它会正常运行并且它与命令
hello
应该做的完全相同。

command-line-interface setuptools python-packaging python-3.10 python-importlib
© www.soinside.com 2019 - 2024. All rights reserved.