Erro when I to try to use import - python-3.x

I am coding an application that has 2 services integrated with rabbitmq(publisher and consumer).
I have a folder lib that contains a class manager_mq, that is used to manage the process of pub/sub of my application.
My structured the directory to be like the image:
In my consumer or publisher .py file, When I try to import manager_mq an error is returned.
My import to be like that:
from services.lib.manager_mq import Manager
However, an error is returned on the console.
Traceback (most recent call last):
File "consumer.py", line 5, in <module>
from services.lib.manager_mq import Manager
ModuleNotFoundError: No module named 'services'
I am tried to use relative import but the error occurs yet.
Traceback (most recent call last):
File "consumer.py", line 5, in <module>
from ..lib.manager_mq import Manager
ImportError: attempted relative import with no known parent package
How can I solve this problem?

Here both absolute and relative imports won't work. For more information, check out Importing from Parent Directory.
In this case it would probably be the easiest to use sys.path to add the lib to the path.
application
├── consumer
│ └── __init__.py
│ └── consumer.py
└── lib
└── __init__.py
└── manager_mq.py
manager_mq.py test code:
class Manager:
def __init__(self) -> None:
print('test')
consumer.py test code:
import sys
sys.path.append("../lib")
from manager_mq import Manager
m = Manager()

Related

Python import error when making a test package

I keep having this error when I launch my code:
File "h:\a_path\source\tests\testClient.py", line 1, in <module>
from .. import client
ImportError: attempted relative import with no known parent package
Here is my program structure:
├source
├── tests
│      ├── __init__.py
│      └── testClient.py
├── __init__.py
├── client.py
I just want to make a test module for the module client.py
Here's the code I have in testClient.py :
from .. import client
def testClient():
client = client.Client()
I have looked up a lot of tutorial online but nothing worked so any help would by highly appreciated.
I tied to change the first line to "import ..client" but it was considered invalid synthax.

How to import classes and function from files within the same dir as main.py in Python 3.9?

I am struggling with importing local source files that reside in the same directory as main.py in Python 3.9. I had it working before but
couldn't tell why it was working. After a while it stopped working.
I created a minimal example to reproduce the problem with the structure shown below.
I have read some available answers that suggest using from . import car in main.py which resulted in the
following Error:
(venv) [.../pyimport_example/productname] python3 ./main.py
Traceback (most recent call last):
File "/Users/myUser/pyimport_example/productname/./main.py", line 1, in <module>
from . import car
ImportError: attempted relative import with no known parent package
Got the same error when using from .car import Car
I have also tried to run main.py as a module as suggested in "Relative imports in Python 3:
(venv) [.../pyimport_example/productname] python3 -m main.py
Traceback (most recent call last):
File "/usr/local/Cellar/python#3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 188, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/usr/local/Cellar/python#3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 111, in _get_module_details
__import__(pkg_name)
File "/Users/myUser/pyimport_example/productname/main.py", line 2, in <module>
from .car import Car
ImportError: attempted relative import with no known parent package
The answer to "Relative imports in Python 3 seems to focus on the case where one want to run a python file as a
script inside a package, which is not the problem I am having.
My sample project
pyimport_example
├── README.md
├── productname
│   ├── __init__.py
│   ├── car.py
│   └── main.py
└── venv
├── bin
├── include
├── lib
└── pyvenv.cfg
content of main.py
from .car import Car
def main():
print("Maria ist cool.")
mycar = Car("Ford", "Mustang", "1966")
mycar.print_car()
if __name__ == '__main__':
main()
contents of car.py
class Car:
def __init__(self, make, model, year_manufacture):
self.make = make
self.model = model
self.year_manufacture = year_manufacture
def print_model(self):
print("{0} {1} {2}".format(self.year_manufacture, self.make, self.model))
Is there a fix without modifying the system path?
You have to modify your __init__.py-File.
In the folder productname you wanna specify what imports you can run from a module on the same level:
from .car import *
Now you should be able to import your file into your main.py with:
from car import Car

How to access functions from another python file in a sub folder?

my folder structure is,
├── handler
│ ├── s3_handler.py
│
└── service
├── service.py
s3_handler file contains many functions which i need to use in service.py
I was trying
from handlers.s3_handler import *
but there is an error.
Traceback (most recent call last):
File "field_mapping_util.py", line 3, in <module>
from handlers.s3_handler import *
ModuleNotFoundError: No module named 'handlers'
how to resolve this
i figured it out.
inside service.py insert,
import sys
sys.path.append("..")
from handler.s3_handler import *

Error when importing variable from different script from different directory

I was working on a project where I was training a neural network and displaying information using a GUI in Python. However, I have a constant problem with importing modules. This is the error I get when trying to run Visualizer.Main
Traceback (most recent call last):
File "/home/user/SplineTrajectoryGenerator/Visualizer/Main.py", line 3, in <module>
from Visualizer.Field import Field
File "/home/user/SplineTrajectoryGenerator/Visualizer/Field.py", line 3, in <module>
from Visualizer.Utils import loadImage
File "/home/user/SplineTrajectoryGenerator/Visualizer/Utils.py", line 3, in <module>
from NeuralNetworks.Pose import Pose2D
File "/home/user/SplineTrajectoryGenerator/NeuralNetworks/Pose.py", line 4, in <module>
from Visualizer.Utils import constraint
ImportError: cannot import name 'constraint'
However, the strange thing is that the variable exists and can be found in Utils.py in the Visualizer folder. I was told that using the _init__.py
allows a directory to be used as a module to import methods and classes from scripts in other directories. I'm still confused about why this error happens when the variable exists. For reference the tree of all the files look like this.
.
├── NeuralNetworks
│ ├── __init__.py
│ ├──Main.py
│ └──Pose.py
├──README.md
└── Visualizer
├── Assets
│ ├── Field.png
│ └── Robot.png
├──Field.py
├── __init__.py
├──Main.py
├──Robot.py
└──Utils.py
In case you need to see the scripts, I have attached the whole folder below with this link. Any help would be greatly appreciated.
You seem to have a cyclic dependency between Visualizer.Utils and NeuralNetworks.Pose`:
from Visualizer.Utils import loadImage
File "/home/user/SplineTrajectoryGenerator/Visualizer/Utils.py", line
3, in
from NeuralNetworks.Pose import Pose2D
File "/home/user/SplineTrajectoryGenerator/NeuralNetworks/Pose.py",
line 4, in
from Visualizer.Utils import constraint
Python does not support cyclic dependencies - and that's actually a GoodThing(tm) since those are design issues (two modules should not depend on each other). The canonical solution is to create a new module for objects (classes, functions, whatever) that are necessary to both modules (ie in your case create a distinct module for 'constraint').

why does import module in same directory gets error

directory structure
test/
__init__.py
line.py
test.py
test.py
from . import line
output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from . import line
ImportError: cannot import name 'line'
I know I can just import line. but it may import standard library in python3.
why did this error happen? does python3 support this syntax?
ps: I'm not in interactive console and test directory has already been a package
I'm not sure if you can import module with the same name as library utilities directly. However, you could consider putting your modules inside a package, so your directory structure would look like:
.
├── main.py
├── package
│   ├── __init__.py
│   ├── line.py
│   ├── test.py
Where __init__.py might have some setup commands (you can omit this file if you have none) and in main.py you can do the following:
from package import line
...
Within the directory package if you'd like to say, import line.py in test.py you can use the syntax:
from . import line
Note relative imports (using the from . notation) will only work inside the script and not in the interactive console. Running the test.py ( if it's using relative imports) directly will also not work, although importing it from main.py will work.

Resources