Import module on Python - python

I'm currently trying to import a module on Python but I'm receiving the following message:
Traceback (most recent call last):
File "test_db_conn.py", line 8, in <module>
from config import config_reader
ModuleNotFoundError: No module named 'config'
Here's the folder structure:
config
- __init.py
- config_reader.py
- config.ini
db_functions
- test_db_conn.py
And the code on 'test_db_conn.py':
# Import modules
from config import config_reader
import pymongo
# Query database and print result
db_client = pymongo.MongoClient(db_url)
db_status = db_client.test
print(db_status)
Are you able to help me with this?
Thank you in advance

You need to append the parent path of your project to the Python module search directory. I replicated your folder structure locally on my dev system, and was able to access a function named config_reader in the config_read.py module, within the config package.
import sys
import pathlib
parent_dir = pathlib.Path(__file__).parent.parent
sys.path.append(parent_dir.__str__())
from config.config_reader import config_reader
config_reader()

Related

ModuleNotFoundError when import from constants file in python

app-main-folder
/local
/__init__.py
/run.py
constants.py
I am trying to import from constants in run.py it's throwing this error
Traceback (most recent call last):
File "local/run.py", line 4, in <module>
from init import app
File "/home/manavarthivenkat/ANUESERVICES--BACKEND/local/init.py", line 5, in <module>
from constants import BaseConstants
ModuleNotFoundError: No module named 'constants'
pip install constants
Try this on your shell
and try running run.py
make sure you load the constants library
this is because Python assumes all your python files are in the current directory. you should tell the compiler you are looking for the file somewhere else.
from app-main-folder.constants import constants # assuming constants is the name of your class in that constants.py
You can use sys.path.append to tell Python interpreter where to search the modules.
First, you can check the current Python path
import sys
from pprint import pprint
pprint(sys.path)
If the path to the directory of constants.py is not included in the output, you can manually add that path, by
import sys
sys.path.append("/path/to/constants.py")

VSCode Python test discovery not loading properly because of imports

Ive got a directory structure:
Business Logic
excel_format_error_checks.py
tests
test_excel_format_error_checks.py
When I set my import of excel_format_error_checks like below, VSCode test discovery gives an error
ModuleNotFoundError: No module named 'Business_Logic'
test_excel_format_error_checks.py
import sys
sys.path.append('..')
from Business_Logic import excel_format_error_checks
class TestExcelFormatErrorChecks(TestCase):
#patch('Business_Logic.excel_format_error_checks.openpyxl')
def test_tgl_not_missing_from_titles(self,mock_openpyxl):
...
If I change the import to from ..Business_Logic import excel_format_error_checks, the test discovery works.
When I then try to run the tests from VSCode test discovery, I get an error because of the #patch path, ModuleNotFoundError: No module named 'Business_Logic'.
When I try to run the tests from the terminal, I get the error
ImportError: Failed to import test module: test_excel_format_error_checks Traceback (most recent call last): File "C:\Users\brady\AppData\Local\Programs\Python\Python310\lib\unittest\loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "C:\Users\brady\Desktop\excel_formatting\excel_format_website\api\tests\test_excel_format_error_checks.py", line 6, in <module> from ..Business_Logic import excel_format_error_checks ImportError: attempted relative import with no known parent package
Questions, 1.why does test discovery only work when i add the .. to the import
2. How can I fix the issue/ fix the patch path
Thanks
In the python language, the import usually only looks in the current directory of the file, and your file directory is obviously not in the same folder.
We can use the following code to provide relative paths. Of course, absolute paths are more commonly used.
import os
import sys
os.path.join(os.path.dirname(__file__), '../')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from BusinessLogic import excel_format_error_checks

I have coded to import python modules into main.py . But I have problem to import

E:\Karya\Python <-- main.py inside here
E:\Karya\packages\extra< -- iota.py inside here
import sys
sys.path.append('E:\Karya')
sys.path.append('E:\Karya\Python')
from ..packages.extra import iota
print(iota.FunI())
Question:call function FunI() by import iota.py
ERROR :
$ C:/Users/ready/AppData/Local/Microsoft/WindowsApps/python3.9.exe e:/Karya/Python/main.py
Traceback (most recent call last):
File "e:\Karya\Python\main.py", line 5, in
from ..packages.extra import iota
ImportError: attempted relative import with no known parent package
detail:
tree directory, main.py inside python folder and iota.py inside extra folder
Error
Code
Just add packages directory to sys.path and import iota from extra
sys.path.append("E:\\Karya\\packages")
from extra import iota
Make sure that there is init.py file in extra directory (and I think it is needed in packages directory too)

Unable to import module from Python

I am trying to import
from app.idol.IP import CONTENT_IP_ADDRESS, CONTENT_PORT
I get the following error
Traceback (most recent call last):
File "testcontent.py", line 1, in <module>
from contentactions import get_dbs
File "C:\Code\Python\xxxxx\app\idol\content\contentactions.py", line 1, in <module>
from app.idol.IP import CONTENT_IP_ADDRESS, CONTENT_PORT
ModuleNotFoundError: No module named 'app'
See directory structure.
All imports are relative to the directory where you run Python. From your screenshot it is clear that you are running testcontent.py from app\idol\content rather than main.py at the source root, so it fails to find the subdirectory app within app\idol\content.
You can instead run Python from C:\Code\Python\K2Associates like this:
python app\idol\content\testcontent.py
__init__.py is imported using a directory. if you want to import it as app you should put __init__.py file in directory named app
another option is just to rename __init__.py to app.py

cannot find module in another directory

I have the project structure:
/hdfs-archiver
/logs
/qe
__init__.py
/tests
__init__.py
archiver.py
/utils
__init__.py
HdfsConnector.py
I am trying to run archiver.py but I am getting this error:
Traceback (most recent call last):
File "qe/tests/HdfsArchiver.py", line 8, in <module>
from qe.utils import HdfsConnector
ImportError: No module named qe.utils
I read around and it seemed like most people that come across this issue fixed it with __init__.py
when I pwd:
$ pwd
/Users/bli1/Development/QE/idea/hdfs-archiver
my PYTHONPATH in .bashrc
export PYTHONPATH=$PYTHONPATH:/Users/bli1/Development/QE/idea/hdfs-archiver
I also tried having my PYTHONPATH as
/Users/bli1/Development/QE/idea/hdfs-archiver/qe
You're trying to import HdfsConnector as a function or class. Include the HdfsConnector module as part of your absolute import:
from qe.utils.HdfsConnector import my_function
You can also import the module:
import qe.utils.HdfsConnector
# or
import qe.utils.HdfsConnector as HdfsConnector
Firstly, you could try a relative import such as
from ..utils import HdfsConnector
You'd also need to run the script as a module and not as a simple python script due to the __name__ being different. This wouldn't require you to modify the path.
You can find more info here.

Categories