为什么在从程序包的根目录运行ModuleNotFoundError: No module named 'helpers'
后执行命令提示符脚本时会收到pip3 install .
? helpers
的位置是c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\mypackage\helpers.py
,那么如何让程序看到那里?
PS C:\> mypackage
Traceback (most recent call last):
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts\mypackage-script.py", line 11, in <module>
load_entry_point('mypackage==0.1.2', 'console_scripts', 'mypackage')()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 572, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2755, in load_entry_point
return ep.load()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2408, in load
return self.resolve()
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2414, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\mypackage\__init__.py", line 16, in <module>
import helpers as h
ModuleNotFoundError: No module named 'helpers'
这是源树:
PS C:\Users\username\source\repos\mypackage> tree /F
Folder PATH listing for volume mydisk
Volume serial number is 01234-A321
C:.
│ .gitignore
│ COPYING
│ MANIFEST.in
│ README.rst
│ setup.py
│
├───mypackage
│ │ helpers.py
│ │ __init__.py
│ │
│ └───__pycache__
│ helpers.cpython-36.pyc
│ __init__.cpython-36.pyc
│
└───tests
itsatrap.py
__init__.py
这是setup.py:
PS C:\Users\username\source\repos\mypackage> cat setup.py
from setuptools import setup, find_packages
from codecs import open
from os import path
path_to_here = path.abspath(path.dirname(__file__))
with open(path.join(path_to_here, 'README.rst'), encoding='utf-8') as readme_file:
readme = readme_file.read()
with open(path.join(path_to_here, 'COPYING'), encoding='utf-8') as license_file:
license = license_file.read()
setup(
name = 'mypackage',
version = '0.1.2',
license=license,
description = 'Who knows',
long_description = readme,
url = 'https://github.com/user/mypackage',
keywords = ['help!'],
packages = find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires = ['matplotlib','numpy'],
extras_require = {
'dev': [''],
'test': [''],
},
entry_points = {
'console_scripts': [
'mypackage=mypackage:main'
],
},
)
感谢任何帮助。在Python中打包对我来说是一个新的领域!从程序包的根目录执行python mypackage/__init__.py
时,该程序运行正常。
答案 0 :(得分:1)
在Python 3中,所有导入都是绝对的。使用完整路径从包中导入模块:
from mypackage import helpers as h
要执行相对导入,请执行以下操作:
from . import helpers as h