Can you please tell me how to do relative import correctly.
Project Structure:
p1
|- x1
| |- __init__.py
| |- x1_module1.py
|- x2
|- __init__.py
|- x2_module1.py
In x2_modules.py
try:
from p1.x1.x1_module import temp_func
except Exception as e:
print('Failed "from p1.x1.x1_module import temp_func"')
print(e)
try:
from .x1.x1_module import temp_func
except Exception as e:
print('Failed "from .x1.x1_module import temp_func"')
print(e)
try:
from ..x1.x1_module import temp_func
except Exception as e:
print('Failed "from ..x1.x1_module import temp_func"')
print(e)
Output:
Failed "from p1.x1.x1_module import temp_func"
No module named 'p1'
Failed "from .x1.x1_module import temp_func"
attempted relative import with no known parent package
Failed "from ..x1.x1_module import temp_func"
attempted relative import with no known parent package
[Finished in 0.2s]
Project Structure:
p1
|- x1
| |- __init__.py
| |- x1_module1.py
|- x2
|- __init__.py
|- x2_module1.py
Edit: The code wasn't following PEP-8 and was hard to read. I, thus, optimized it.
Please try this code:
import sys
import os
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(
os.path.realpath(
os.path.join(
os.getcwd(),
os.path.expanduser(__file__)
)
)
)
sys.path.append(
os.path.normpath(
os.path.join(
SCRIPT_DIR,
PACKAGE_PARENT
)
)
)
from x1.x1_module import tempfunction
It works
Regards Ishaan Kapoor
If your python script is called from the p1 directory, this should work:
from x1.x1_module1 import temp_func
To see a list of where python is searching for your module, use this:
import sys
print(sys.path)
The first entry of sys.path should be the directory your script is running from, which I'm assuming is p1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.