1

In the current working directory , i have following structure

Project
   __init__.py
   -RestApi
           __init__.py
           app.py
           query_generator
   -testfolder
           __init__.py
           test1.py

I want to call query_generator from test1.py , I tried calling

 from . RestApi.query_generator import *

but getting following error

ImportError: attempted relative import with no known parent package

This question might be duplicate of following Importing files from different folder , Python relative-import script two levels up, Attempted relative import with no known parent package . But I am not able to solve it for my current problem

qaiser
  • 2,770
  • 2
  • 17
  • 29

2 Answers2

1

Try using below import:

from Project.RestApi.query_generator import *
Astik Gabani
  • 599
  • 1
  • 4
  • 11
  • from ProjectAware.RestApi.query_generator import * ModuleNotFoundError: No module named 'ProjectAware' – qaiser Jul 14 '20 at 02:58
  • getting ModuleNotFoundError – qaiser Jul 14 '20 at 02:59
  • Did you executing file like: python testfolder/test1.py ? – Astik Gabani Jul 14 '20 at 03:04
  • Yes I am doing that – qaiser Jul 14 '20 at 03:09
  • Can you check your python path and verify that your CWD is present in python path after executing this file? Use sys module for this. Just print(sys.path) – Astik Gabani Jul 14 '20 at 03:11
  • i have added the path using sys.path.insert(1, 'U:\\ProjectAware') – qaiser Jul 14 '20 at 03:34
  • ['u:\\ProjectAware', 'C:\\Anaconda3\\envs\\dbconnect\\python37.zip', 'C:\\Anaconda3\\DLLs', 'C:\\Anaconda3\\lib', 'C:\\Anaconda3\\envs\\dbconnect', 'C:\\Anaconda3', 'C:\\Anaconda3\\lib\\site-packages', 'C:\\Anaconda3\\lib\\site-packages\\restapi-0.0.1-py3.7.egg', 'C:\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda3\\lib\\site-packages\\Pythonwin'] – qaiser Jul 14 '20 at 03:35
  • ModuleNotFoundError: No module named 'ProjectAware' , still getting same error – qaiser Jul 14 '20 at 03:36
  • This is strange. Bcz if your CWD is present in python path. there should not be any error like ProjectAware. – Astik Gabani Jul 14 '20 at 03:45
  • After adding RestApi to path its worked fine. Thank u – qaiser Jul 14 '20 at 04:31
1

There are multiple ways to achieve this. you can add path till Project dir in your PYTHONPATH variable

export PYTHONPATH=$PYTHONPATH:<path_leading_to_Project>/Project

Then inside test1.py you can import the query_generator module using:

from RestApi.query_generator import *

Advantage of doing in such a way is if you execute your script from any working directory, it will work

Rachit Tayal
  • 1,190
  • 14
  • 20