简体   繁体   English

pip安装后Python自制包导入错误

[英]Python homemade package import error after pip install

If I make a very simple package like this (with empty __init__.py files): 如果我这样制作一个非常简单的包(带有空的__init__.py文件):

package_name/
    package_name/
         sub_module/
              __init__.py
              file.py  
         __init__.py
    setup.py

When I start a Python shell at the root of this project, and do: 当我在该项目的根目录下启动Python Shell并执行以下操作时:

import package_name.sub_module.file

everything goes well and I can use the functions in file.py . 一切顺利,我可以使用file.py的功能。 But if I send this project on a GitLab, and pip install it in another local project and import it the same way, I get the following error: 但是,如果我在GitLab上发送此项目,然后将其pip安装在另一个本地项目中,并以相同的方式导入,则会出现以下错误:

ModuleNotFoundError: No module named 'package_name.sub_module'

I tried to modify the __init__.py files in many ways but I can't find something working. 我试图以多种方式修改__init__.py文件,但找不到任何有效的方法。 I don't understand why this happen. 我不明白为什么会这样。

EDIT: Here is the content of the setup.py file: 编辑:这是setup.py文件的内容:

from setuptools import setup

setup(name='package_name',
      version='0.1',
      description='My package',
      url='https://gitlab.myserver.com/package_name',
      author='Me',
      author_email='me@myserver.com',
      license='MIT',
      packages=['package_name'],
      install_requires=[
          'another_package_1',
          'another_package_2'
      ],
      zip_safe=False)

To install the package with pip, I use the command: 要使用pip安装软件包,请使用以下命令:

pip install git+https://gitlab.myserver.com/package_name.git

look on this site https://docs.python.org/3/distutils/setupscript.html 在此网站上查看https://docs.python.org/3/distutils/setupscript.html
you have to declare every subfolder in the project structure 您必须声明项目结构中的每个子文件夹

packages=['an_example_pypi_project', 'tests'], 包= ['an_example_pypi_project','测试'],

|-- an_example_pypi_project
|   |-- __init__.py
|   |-- useful_1.py
|   |-- useful_2.py
|-- tests
|-- |-- __init__.py
|-- |-- runall.py
|-- |-- test0.py

|-- an_example_pypi_project
|   |-- __init__.py
|   |-- useful_1.py
    |-- subfolder
|   |   |-- useful_2.py
|-- tests
|-- |-- __init__.py
|-- |-- runall.py
|-- |-- test0.py

packages=['an_example_pypi_project', an_example_pypi_project.subfolder, 'tests'], packages = ['an_example_pypi_project',an_example_pypi_project.subfolder,'tests'],

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

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