如何导入和使用我的 python 包? my_package_file.py请求.pyscript.py

问题描述

问题

我正在尝试发布和使用我创建的包,这是目录结构

my_package_folder
|
|-build
|-dist
|-setup.py
|-my_package_name
||
||-my_package_file.py
||-__init__.py
||
||-request_folder
|||
|||-request_file.py
|||-__init__.py

setup.py

​​>
VERSION = '1.0.0'
DESCRIPTION = 'api package'
LONG_DESCRIPTION = 'longer package description'

# Setting up
setup(
    name="my_package_settings_name",version=VERSION,author="John Smith",author_email="<email@email.com>",url='https://github.com/the-project/project-name',description="api client package",long_description="api client",packages=find_packages(),install_requires=[],keywords=['python'],classifiers=[
        "Development Status :: 3 - Alpha","Intended Audience :: Developers","Programming Language :: Python :: 3","Operating System :: MacOS :: MacOS X","Operating System :: Microsoft :: Windows",]
)

my_package_file.py

from request_folder.request_file import Request

class Api:
    def __init__(self): #not important implementation details

请求.py

import json
import urllib.parse
import urllib.request
from urllib.request import urlopen


class Request:
    def __init__(self): # unimportant implementation details

然后我运行以下命令:

python setup.py sdist bdist_wheel
twine upload dist/*

这会将包上传到 pypi 并成功。但是,当我尝试下载和使用我的包时,我无法导入和使用导入失败的代码

pip install my_package_settings_name==1.0.0

script.py

from  my_package_settings_name import Api

导入找不到包。我不是 Python 中的佼佼者,所以我认为我缺少一些小东西。任何帮助或建议将不胜感激。

解决方法

让您感到困惑的问题是您的包名实际上与其包含的python模块不同。您已上传包含模块 my_package_name 的“my_package_settings_name”。因此,假设您的 Api 类是在 my_package_name/init.py 内定义的,您应该使用:

from my_package_name import Api