【问题标题】:Python locally installed package, module not definedPython 本地安装包,模块未定义
【发布时间】:2023-02-04 04:43:33
【问题描述】:

我有一个像这样设置的本地包:

D:.
|   .gitignore
|   LICENSE
|   pyproject.toml
|   README.md
|   requirements.txt
+---.venv
|   |   ...            
+---mypackage
|   |   __init__.py
|   +---moduleA
|   |   |   module_a_src.py
|   |   |   module_a_helpers.py          
|   +---tools
|   |       tools.py 
\---tests

__init__.py 文件为空。 tools.py 文件包含以下内容:

def working(string):
    print(string)

print("here i am")

我使用pip install -e .以编辑模式将包安装到我的本地venv

我还没有/想要入口点。我可以从 shell 运行以下命令,它按预期工作:

$ py -c "from mypackage.tools import tools; tools.working('foo')"
here i am
foo
(.venv)

但是,我希望能够运行py -c "import mypackage; tools.working('foo')"。我尝试将以下内容添加到 __init__.py 文件中:

from tools import tools

# other things that didn't work and return the same error:
# from .tools import tools
# import tools.tools
# from . import tools

但我明白了:

$ py -c "import mypackage; tools.working('foo')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'tools' is not defined
here i am
(.venv)

我尝试在工具文件夹中添加一个空的__init__.py,但没有成功。

pyproject.toml 包含这个,如果重要的话:

[tool.setuptools]
include-package-data = true

[tool.setuptools.packages.find]
where = [".", "mypackage"]

【问题讨论】:

    标签: python package


    【解决方案1】:

    使用相对导入,而不是绝对导入。

    from .tools import tools
    

    【讨论】:

    • 这将返回相同的错误
    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 2016-09-08
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多