python module not found error no module named - python

I have a few seperate pythone file and I am using them to import another py file. Modules that trying to import them are in seperate folder I code sample is below
from tez.library.image_crop import ImageCrop
from tez.library.image_process import ImageProcess
from tez.library.image_features import ImageFeatures
from tez.const.application_const import ApplicationConst
from tez.library.file_operation import FileOperation
this code is in where I want to start the py file using commond line as "python samples1.py" and thrown an error as below
Traceback (most recent call last): File "samples1.py", line 1, in
from tez.library.image_crop import ImageCrop ModuleNotFoundError: No module named 'tez'
folder structure :
.tez
-- library
---- image_crop.py
---- image_process.py
---- image_features.py
--src
---- samples1.py
Python version : 3.8
Pip : 20.0.2
Windows 10 Pro 1909

If you are building a package called tez (and since you tried to import it I think you are). Then everything with tez needs to refer to itself locally. All the files in the tez package need to refer to each other with the "." and ".." imports.
In samples1.py:
from ..library.image_crop import <something>
EDIT:
It sounds like you are misunderstanding how python imports things. When you run "import X" in a python script, then python looks for a package named X under sys.path. You can append to sys.path at the top of your script if you have a custom package to look for.
import sys
sys.path.append(<directory of tez>)
import tez
However, it is strongly recommended that you should not be importing from a file that is under the directory structure of the package name. If "examples" is a directory of examples that use the package "tez" then "examples" should be located outside the package "tez". If "examples" is inside the package "tez", then "examples" should be doing local imports "with-in" the package.
Getting a handle on package use can be tricky.

sample.py can't see above of src folder, but you can tell Python to do this.:
import sys
import os
tez = os.path.dirname(os.path.dirname(__file__))
# __file__ is path of our file (samples.py)
# dirname of __file__ is "src" in our state
# dirname of "src" is "tez" in our state
sys.path.append(tez) # append tez to sys.path, python will look at here when you try import something
import library.image_crop # dont write "tez"
But this is not a very good design I think.

Related

Import issue when running tests from within a project with cython code

I have a Python library with Cython code.
When I compile the library I manage to import it successfully and use it in other projects. But when I write tests (which are executed from within the library's project root path), there's an import issue and the Cython code cannot be imported.
I have removed the project's path from sys.path so the import system will prefer to import from site-packages, and the import issue indeed occur in site-packages, but still, it happens only when I execute a file under the library's path, but does not happen when I import the library and execute a file under another project path.
Here's the project's structrue:
libname:
-libname/
call_mapping.pyx
main.py (imports call_mapping.pyx)
-tests/
test_libname.py (imports libname, raises ImportError because main.py can't import call_mapping.pyx)
But on another project, the error does not occur:
another-project:
f.py (import libname successfully)
The error:
from libname.main import LibnameSettings
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/libname-0.1.9-py3.10-macosx-10.9-universal2.egg/libname/main.py", line 6, in <module>
from libname.call_mapping import (
ModuleNotFoundError: No module named 'libname.call_mapping'
Any ideas on how to fix this? Thanks!

Unable to Import a file from Parent Directory

My file structure is as follows:
monitor/
core/
database.py
processor.py
timekeeper.py
jobs/
jobA.py
jobB.py
setup.py
From jobA.py I import like this:
from core.database import Database
from core.timekeeper import Timekeeper
from core.processor import Processor
While at database.py, processor.py and timekeeper.py I import setup.py.
Get the following error when I run jobA.py:
root#test:/var/www/python/monitor# python3 jobs/jobA.py
Traceback (most recent call last):
File "jobs/jobA.py", line 2, in <module>
from core.database import Database
ModuleNotFoundError: No module named 'core'
To allow import core or import core.database (without the relative dots or double-dots) the parent directory of core should either be the current directory, or be included on sys.path. You appear to have a setup.py. Conventionally that means a file that performs installation and packaging tasks via the setuptools or distutils packages. If that is indeed the role it performs, perhaps you need to run it. One way to run it would be to issue (from the command-line outside Python) the command pip install -e /path/to/monitor. Assuming setup.py was written correctly, this will ensure that the core package, in its current location, is lastingly made available for the default Python distribution. Next time you launch Python, /path/to/monitor will be on sys.path and import core will work from (almost) anywhere.
Add
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
to the top of your jobA.py file. If you are using python 3.3+, you do not need an __init__.py file. It needs to be above your other import statements.
From this answer you can use 2 dots to import from a directory above. So you could potentially use:
from .core.database import Database
from .core.timekeeper import Timekeeper
from .core.processor import Processor
Python 3.3+ you don’t need an __init__.py file so I don’t believe just adding one will help.
What module are you trying to use? Maybe your module is not compatible with Python 3.

ModuleNotFoundError: No module named 'Src' - When I run a Pytest

I am building a discord bot and I am having trouble importing the code with the functions that I want to test.
When I run my MemberRepositoryTest.py file it gives me the following error:
ModuleNotFoundError: No module named 'Src'
MemberRepositoryTest.py (/Tests/Src/Repositories/)
import pytest
from Src.Repositories import MemberRepository # <--- This line is failing.
# TODO: Implement tests
My folder structure is this on this link - https://imgur.com/a/Rh65iJY
The tests structure is:
Tests/Src/Repositories/MemberRepositoryTest.py (Mirrors Src)
I am unsure why it is not finding my modules so I can import the classes and functions.
From my research online I think it may be a problem with my init.py files. However, being new to Python, I do not understand this fully. I read the Python documentation which explained it creates a package with the files inside as the modules. This means I have imported each file in the directory to the init.py file. However, I am still getting this issue.
Init file (on root directory):
import Src
Init file (/Src/):
import Cogs
import Entities
import Models
import Queries
import Repositories
import AppConfig
import DatabaseConnection
Init file (/Src/Repositories):
import GuildRepository
import MemberRepository
I run this from the root directory of the project (documents/rush_bot). The command I run to execute the test file is pytest Tests/Src/Repositories/MemberRepository.py
My Python Path Environment is:
C:\WINDOWS\SYSTEM32\python27.zip
C:\Python27\DLLs
C:\Python27\lib
C:\Python27\lib\plat-win
C:\Python27\lib\lib-tk
C:\Python27
C:\Python27\lib\site-packages
Python is failing to find your package since it is not in the PYTHONPATH.
You can either add your project folder to the PYTHONPATH or .. If you add . then Python will always look for packages inside the current directory.
By the way, in this Init file (/Src/Repositories) you are importing modules without the full path.
import Src.Repositories.GuildRepository
import Src.Repositories.MemberRepository

Create and import a custom python package - import doesn't work in the root

I'm totally new to Python, and I want to create my first Python library for peronal uses.
I'm using Python 2.7.5, and running the IDLE interface.
So far, what I understood from the documentation and related questions is that:
Python goes through a list of directories listed in sys.path to find scripts and libraries
The package directory must contain a __init__.py file, which can be empty
The module I want to create should be a modulename.py file with the code inside the package directory
(Sources: http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html --- https://docs.python.org/2/tutorial/modules.html)
And here is what I tried that fails:
Created a personal package directory C:\....\pythonlibs
Created a subpackage dir C:\....\pythonlibs\package
Created the __init__.py file inside both folders
Created the mymodule.py file in the packacge dir
And then in the IDLE used this code:
import sys
sys.path.append(r'C:\....\pythonlibs')
First issue:
Currently I have to do this append every time I enter the IDLE. How can I keep the directory in sys.path permanently just as there are a lot of other directories there?
Then I tried importing my package:
import pythonlibs #fails!! why?
import pythonlibs.package #fails!! why?
import package #works
The error is: ImportError: No module named pythonlibs
Second issue?
This seems to be against the documentation, why can't I import from the root pythonlibs folder?
With line
sys.path.append(r'C:\....\pythonlibs')
you are instructing interpreter to start looking for modules (libraries) in this directory. Since this directory does not contain pythonlibs folder (the parent does), it can't import it.
Similarly - because it contains the module package, it can import it.

How to import a module from a directory on level above the current script

For my Python application, I have the following directories structure:
\myapp
\myapp\utils\
\myapp\utils\GChartWrapper\
\myapp\model\
\myapp\view\
\myapp\controller\
One of my class in \myapp\view\ must import a class called GChartWrapper. However, I am getting an import error...
myview.py
from myapp.utils.GChartWrapper import *
Here is the error:
<type 'exceptions.ImportError'>: No module named GChartWrapper.GChart
args = ('No module named GChartWrapper.GChart',)
message = 'No module named GChartWrapper.GChart'
What am I doing wrong? I really have a hard time to import modules/classes in Python...
The __init__.py file of the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line:
from GChartWrapper.GChart import *
Is it necessary to have the GChartWrapper included package in your package directory structure?
If so, then one thing you could do is adding the path where the package resides to sys.path at run time. I take it myview.py is in the myapp\view directory? Then you could do this before importing GChartWrapper:
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
If it is not necessary to have it in your directory structure, it could be easier to have it installed at the conventional location. You can do that by running the setup.py script that's included in the GChartWrapper source distribution.
You don't import modules and packages from arbritary paths. Instead, in python you use packages and absolute imports. That'll avoid all future problems.
Example:
create the following files:
MyApp\myapp\__init__.py
MyApp\myapp\utils\__init__.py
MyApp\myapp\utils\charts.py
MyApp\myapp\model\__init__.py
MyApp\myapp\view\__init__.py
MyApp\myapp\controller\__init__.py
MyApp\run.py
MyApp\setup.py
MyApp\README
The files should be empty except for those:
MyApp\myapp\utils\charts.py:
class GChartWrapper(object):
def __init__(self):
print "DEBUG: An instance of GChartWrapper is being created!"
MyApp\myapp\view\__init__.py:
from myapp.utils.charts import GChartWrapper
def start():
c = GChartWrapper() # creating instance of the class
MyApp\run.py:
from myapp.view import start
start()
That's all! When you run your entry point (run.py) it calls a function on the view, and that creates an instance of the GChartWrapper class. Using this structure you can import anything anywhere and use it.
To complement, in MyApp\setup.py you write an installation program for the MyApp\myapp package. Use distutils to write it:
from distutils.core import setup
setup(name='MyApp',
version='1.0',
description='My Beautiful Application',
author='Martin',
author_email='martin#xxxxxxx.com',
url='http://stackoverflow.com/questions/1003843/',
packages=['myapp'],
scripts=['run.py']
)
That is enough. Now when people download the MyApp folder, they can just install it using setup.py and run it using run.py. Distutils can generate packages in a number of formats including windows installable .EXE
It's the standard way of distributing python packages/applications.
You can change the path where python looks for files.
At the top of your source file, add:
import sys
sys.path.append("..")
Or alternatively change the environment variable:
export PYTHONPATH=..
Or starting in python 2.5 (again assuming myview is in myapp\view:
from __future__ import absolute_import
from ..utils.GChartWrapper import *
See: http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports
GChartWrapper is also available from PyPI so you can use easy_install or pip to install the module:
sudo pip install GChartWrapper==0.9
It will then be automatically added to your PYTHONPATH and then you can remove it from your /myapp/utils directory. If you can't use sudo, look at using virtualenv (and virtualenvwrapper).

Categories