简体   繁体   English

Python:在安装的 python 自定义包中导入失败

[英]Python: import failing in installed python custom package

I have a python package created using setup.py and then installed in a virtual environment.我有一个使用 setup.py 创建的 python 包,然后安装在虚拟环境中。 The directory structure is:目录结构为:

root
 |
 +-- setup.py
 |
 +-- package
      |
      +-- __init__.py
      |
      +-- main.py
      |
      +-- common
           |
           +-- __init__.py
           |
           +-- helper.py

I have a method that exist in helper.py and importing in main.py by from common.helper import func .我有一个存在于helper.py并通过from common.helper import func导入main.py的方法。 After creating a wheel of this and installing and using that as a global module I am getting an import error for common .在创建一个轮子并将其安装并用作全局模块后,我收到common的导入错误。 But changing the import statement to from package.common.helper import func works.但是将 import 语句更改为from package.common.helper import func是可行的。 Is there a way to define the common as a local submodule to package so that even if is installed as a package it uses common as a local submodule.有没有办法将common定义为要package的本地子模块,这样即使作为包安装,它也会使用common作为本地子模块。

You should use from .common.helper import func .您应该使用from .common.helper import func You code is failing because it cannot recognise common as a package globally, since it is subpackage to package directory.您的代码失败了,因为它无法将 common 识别为全局包,因为它是package目录的子包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM