Why would I receive a ModuleNotFoundError: No module named 'helpers' when I execute the command prompt script after running pip3 install . from my package's root directory? The location of helpers is c:\users\username\appdata\local\programs\python\python36-32\lib\site-packages\mypackage\helpers.py so how to I get the program to look there?
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'
Here is the source tree:
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
Here is the 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'
],
},
)
Any help is appreciated. Packaging in Python is new territory for me! This program did run correctly when doing python mypackage/__init__.py from the package's root directory.
In Python 3 all imports are absolute. Use full path to import a module from a package:
from mypackage import helpers as h
To perform relative import do it explicitly:
from . import helpers as h
Related
I'm trying to build a package where specific modules call other modules. Example of the structure of the package:
provapackage/
├── main.py
└── pippo
├── derivative_functions.py
├── functions_pippo.py
└── __init__.py
content of the functions_pippo module:
def add(x,y):
return x+y
content of the derivative_functions module:
from functions_pippo import add
def add_lst(l):
n=0
for i in l:
n = add(n,i)
return n
content of the main.py file:
from pippo.derivative_functions import add_lst
lst = [1,2,3,4]
print(add_lst(lst))
when I run main.py I get this error:
Traceback (most recent call last):
File "/home/g/Documents/provapackage/main.py", line 1, in <module>
from pippo.derivative_functions import add_list
File "/home/g/Documents/provapackage/pippo/derivative_functions.py", line 1, in <module>
from functions_pippo import add
ModuleNotFoundError: No module named 'functions_pippo'
It seems like python cannot find the functions_pippo module even if it's in the same folder. But when I run derivative_functions.py I don't gat any error message. Is it an import problem?
See this answer here
from .functions_pippo import add
not
from functions_pippo import add
I learning python module , I want to put some file to one mudole dir, and then call it at the project root. but it not work. I try to solve it , but it still not success!
what is the problem ?
├── calculator
│ ├── __init__.py
│ ├── addTwo.py
│ ├── mulTwo.py
│ └── sum.py
└── main.py
# calculator/__init__.py
#nothing
# calculator/addTwo.py
def addFunc(lhs, rhs):
return lhs + rhs
# calculator/mulTwo.py
def mulFunc(lhs, rhs):
return lhs * rhs
# calculator/sum.py
import addTwo
def sumFunc(arg1, arg2, arg3):
ans = addTwo.addFunc(arg1,arg2)
ans = addTwo.addFunc(ans,arg3)
return ans
#main.py
from calculator import addTwo
from calculator import mulTwo
from calculator import sum
def test():
print(addTwo.addFunc(1,2))
print(mulTwo.mulFunc(1,2))
print(sum.sumFunc(1,2,3))
if __name__ == '__main__':
test()
run it
cong.lin#C02YN3P4LVCK ~/Program/python/module_test python3 main.py
Traceback (most recent call last):
File "main.py", line 4, in <module>
from calculator import sum
File "/Users/cong.lin/Program/python/module_test/calculator/sum.py", line 1, in <module>
import addTwo
ModuleNotFoundError: No module named 'addTwo'
✘ cong.lin#C02YN3P4LVCK ~/Program/python/module_test
You have to provide PYTHONPATH to root of your project
Try
export PYTHONPATH=$PWD
before running
python3 main.py
I know many similar questions have been asked, but I feel like I've tried everything and I keep getting the same error. I followed this article https://gehrcke.de/2014/02/distributing-a-python-command-line-application/ and I think I've done the same. Anyway, here's my project structure:
nc-textmanager-tool/
├── nc_textmanager
│ ├── gui/
│ ├── textmanager/
│ ├── __init__.py
│ ├── __main__.py
│ └── nc_main.py
├── LICENSE
├── bundles.yaml
├── env.yaml
├── requirements.txt
├── README.rst
└── setup.py
And here's the content of setup.py
import setuptools
with open("README.md", "r", encoding="utf-8") as f:
long_desc = f.read()
with open("requirements.txt", "r", encoding="utf-8") as f:
requirements = f.readlines()
setuptools.setup(
name="nc-textmanager",
version="1.1.11",
author="XXX",
author_email="XXX",
description="A simple tool for viewing and searching through keys and values used by TextManger in NC projects.",
long_description=long_desc,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
entry_points={
"console_scripts": ['nc_textmanager = nc_textmanager.nc_main:run']
},
url="???",
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.8',
install_requires=requirements
)
Installing it by running python .\setup.py install works fine, but when I try to run my nc_textmanager script from the console, I get this error:
> nc_textmanager
Traceback (most recent call last):
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\Scripts\nc_textmanager-script.py", line 33, in <module>
sys.exit(load_entry_point('nc-textmanager==1.1.11', 'console_scripts', 'nc_textmanager')())
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\Scripts\nc_textmanager-script.py", line 25, in importlib_load_entry_point
return next(matches).load()
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\lib\importlib\metadata.py", line 77, in load
module = import_module(match.group('module'))
File "C:\Users\SEHE\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'nc_textmanager.nc_main'
I did try to put the nc_textmanager-script.py file in my project root and execute it there, and everything works fine. I'm thus thinking there's an issue with the working directory...
Using python 3.8 on Windows 10.
I have got a problem with circular imports in Python 3.9.
I know there are numerous articles, questions and answers about this topic and I really have read a lot of them and about how to circumvent but I cannot figure out why it happens in my case. As far as I have understood one can circumvent circular imports by doing absolute imports:
This is my Stacktrace:
partially initialized module 'myproject.myapp.service.linepattern.corner' has no attribute 'Corner' (most likely due to a circular import)
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/line.py", line 8, in Line
def __init__(self, cornerRight: cc.Corner, cornerLeft: cc.Corner) -> None:
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/line.py", line 7, in <module>
class Line(ABC):
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/corner.py", line 2, in <module>
import myproject.myapp.service.linepattern.line as cl
File "/mnt/d/User/Programming/MyProject/myproject/myapp/service/linepattern/cornermanager.py", line 2, in <module>
import myproject.myapp.service.linepattern.corner as cc
File "/mnt/d/User/Programming/MyProject/myproject/tests/myapp/test_cornermanager.py", line 3, in <module>
import myproject.myapp.service.linepattern.cornermanager as cm
and this is my file hierarchy
/mnt/d/User/Programming/MyProject
├── manage.py
├── myproject
│ ├── myapp
│ │ ├── __init__.py
│ │ ├── service
│ │ │ └── linepattern
│ │ │ ├── cornermanager.py
│ │ │ ├── corner.py
│ │ │ ├── line.py
│ │ │ ├── __init__.py
│ ├── settings.py
│ ├── tests
│ │ ├── myapp
│ │ │ ├── __init__.py
│ │ │ └── test_cornermanager.py
and finally my code
cornermanager.py
import myproject.myapp.service.linepattern.corner as cc
class CornerManager:
def __init__(self) -> None:
self.cornerList: List[cc.Corner]
for i in range(1, 2):
self.cornerList.append(cc.Corner(i, self))
for corner in self.cornerList:
corner.initializeLines()
def corner(self, cornerNr: int) -> cc.Corner:
return self.cornerList[cornerNr - 1]
corner.py
import myproject.myapp.service.linepattern.cornermanager as cm
import myproject.myapp.service.linepattern.line as cl
class Corner:
def __init__(self, cornerNumber: int, cornerManager: cm.CornerManager) -> None:
self.cornerNumber = cornerNumber
self.cornerManager = cornerManager
self.lineSet: Set[cl.Line]
def initializeLines(self) -> None:
#Add lines to the corner including its neighbor
if self.cornerNumber == 1:
self.lineSet.add(cl.Line(self, self.cornerManager.corner(2)))
elif self.cornerNumber == 2:
self.lineSet.add(cl.Line(self, self.cornerManager.corner(2)))
def addLine(self, line: cl.Line) -> None:
#Remove line from both corners
for corner in cl.cornerPair():
corner.lineSet.add(line)
def removeLine(self, line: cl.Line) -> None:
#Remove line from both corners
for corner in cl.cornerPair():
corner.lineSet.remove(line)
line.py
import myproject.myapp.service.linepattern.corner as cc
class Line:
def __init__(self, cornerRight: cc.Corner, cornerLeft: cc.Corner) -> None:
self.rightCorner = cornerRight
self.leftCorner = cornerLeft
def cornerPair(self) -> Tuple[cc.Corner, cc.Corner]:
#Return both corners
return (self.rightCorner, self.leftCorner)
With the code you put in the question (three separated modules), by including the following code at the top of each file should be able to fix the problems:
from __future__ import annotations
In short this code will treat annotations as strings. You can read more about this at: Type hint of the enclosing class and Evaluation of annotations.
For the errors, this actually how Python executes your modules (start from cornermanager.py):
import corner. With this Python first saves the module in its internal module (sys.modules) before running the imported module code.
In corner.py itself, the first two lines are import statement, so let's start with import cornermanager. Again, Python saves the module in its internal module then executes the code in cornermanager.
Back to cornermanager.py. As we know first line of this module is import corner, but because Python already saved this module (corner) in its internal module, it doesn't import it the second time. That is, Python skips it and executes code below this line. Interestingly, because corner hasn't executed all its code but the first line (import cornermanager), attempt to fetch its Corner class will not succeed.
I need a little help with python packaging. I known similar questions has been already asked, but I could not find the solution for my problem.
Here is the output of tree:
.
├── env
├── prala
│ ├── __init__.py
│ └── __main__.py
└── setup.py
setup.py:
from setuptools import setup, find_packages
setup(
name='prala',
version='0.5',
description='Practice Language',
url='http://github.com/*/*',
author='*',
author_email='*#*.com',
license='MIT',
classifiers =[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
],
packages=find_packages(),
entry_points = {
'console_scripts': ['ppp=__main__:main'],
},
zip_safe=False)
__main__.py:
def main():
print("hello world")
if __name__ == "__main__":
main()
I did the following:
I activated the virtualenv in the root: $ source env/bin/activate
I built the dist and installed it: (env) $ python setup.py install
I run the entry point: (env) $ ppp
Unfortunately I got error instead of the 'hello world' message:
Traceback (most recent call last):
File "/home/akoel/Projects/python/delete/env/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2332, in resolve
return functools.reduce(getattr, self.attrs, module)
AttributeError: module '__main__' has no attribute 'main'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/akoel/Projects/python/delete/env/bin/ppp", line 11, in <module>
load_entry_point('prala==0.5', 'console_scripts', 'ppp')()
File "/home/akoel/Projects/python/delete/env/lib/python3.6/site-packages/pkg_resources/__init__.py", line 480, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/akoel/Projects/python/delete/env/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2693, in load_entry_point
return ep.load()
File "/home/akoel/Projects/python/delete/env/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2324, in load
return self.resolve()
File "/home/akoel/Projects/python/delete/env/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2334, in resolve
raise ImportError(str(exc))
ImportError: module '__main__' has no attribute 'main'
Can anyone help me showing what did I miss?
I found the problem:
In the entry_points in the setup.py I forgot to put the project name for the console_settings:
entry_points = {
'console_scripts': ['ppp=prala.__main__:main'],
},