Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import module from same level directory in python

as the question, i have my directory map like this

enter image description here

enter image description here

the formatOutput contain some function for better print now, i want use a function in module printChecked.py in package formatOutput from findInfoSystem.py

i have tried create __init__.py in all folder to treat python it is a package (the advice i get from previous answer other post) but it always failed.

case 1: from formatOutput.printChecked import print_checked_box

error is: ModuleNotFoundError: No module named 'formatOutput'

case 2: from dttn.formatOutput.printChecked import print_checked_box

error is ModuleNotFoundError: No module named 'dttn'

case 3: from ..formatOutput.printChecked import print_checked_box

error is ImportError: attempted relative import with no known parent package

i don't want to use the sys.path method because i think it is not the good way to solve problem.

Help me please !

like image 743
Thanh Tuấn Lê Avatar asked Jul 20 '26 22:07

Thanh Tuấn Lê


1 Answers

i found something very weird. I'm not import direct in module file but import to init.py file of package and then import to module file from packages name and it work. it like that:

from __init__.py of systemInfo package:

import sys,os
from formatOutput import prettyAnnounce,prettyParseData
current_directory = os.getcwd() 
# sys.path.insert(1, current_directory+"/formatOutput/")
# sys.path.insert(1,current_directory+"/")

then in findInfoSystem.py module, im imported again like this:

from systemInfo import current_directory, prettyAnnounce as prCh , prettyParseData as prPD

yeah, now it's work like a charm. :))) i even not sure how

like image 57
Thanh Tuấn Lê Avatar answered Jul 22 '26 12:07

Thanh Tuấn Lê