1

Let me start off by saying I know this issue has already been discussed, but I could not find a solution that was similar to my case.

I have a directory structure like the following:

  • project/
    • tools
      • my_tool
        • tool_name.py
    • tests
      • lib
        • constants.py
        • my_test.py
        • common/
          • check_lib.py

I need to import constants.py, check_lib.py, and tool_name.py into my_test.py using relative paths. Is there a way to do this even though several of my modules are in various depths within different directories in my project? I am trying to do this directly in the code with a "from module.path import module" type of import. Any help is greatly appreciated!

MY solution was the following:

tool_name.py

print("tool_name.py imported")

constants.py

print("constants.py imported")

check_lib.py

print("check_lib.py imported")

my_test.py

import constants
import common.check_lib

import sys
import os
sys.path.append(os.path.abspath('test_project/tools/my_tool'))

import tool_name

output :

constants.py imported
check_lib.py imported
tool_name.py imported
my_test.py is running

Josh Sullivan
  • 107
  • 1
  • 11

2 Answers2

0

Using PYTHONPATH=., go to the directory one level up from "project".

Invoke your code with somewhat long names, e.g. $ python -m project.tools.my_tool.tool_name. That way "tools" code will be allowed to access "tests", since it's still within "project".

J_H
  • 17,926
  • 4
  • 24
  • 44
  • Thank you for the response, I should have mentioned I am trying to do this directly in the code with a "from module.path import module" type of import. – Josh Sullivan Jul 22 '19 at 21:48
-1

tool_name.py

print("tool_name.py imported")

constants.py

print("constants.py imported")

check_lib.py

print("check_lib.py imported")

my_test.py

import constants
import common.check_lib

from sys import path as external_import

external_import.append("../../tools/my_tool/")
import tool_name

print("my_test.py is running")

output :

constants.py imported
check_lib.py imported
tool_name.py imported
my_test.py is running
Er. Harsh Rathore
  • 758
  • 1
  • 7
  • 21
  • Thank you for your response, I will give this a try tomorrow and report back if this approach works with my scenario otherwise ill clarify my question better. But this seems to be what i was looking for! – Josh Sullivan Jul 22 '19 at 21:52
  • Okay. Be sure that you are placing all the files into right directories. – Er. Harsh Rathore Jul 23 '19 at 14:39
  • I couldn't get it to append the path the exact way you had set it, however, this led me pretty close to the right answer i was looking for so I gave you an upvote. Thank you for your help! – Josh Sullivan Jul 23 '19 at 16:04
  • **../** is used to jump out from current folder. 1st for **lib** 2nd for **tests**. Now we are in our **project** folder. Now we can choose child directory in which we want to deep inside. – Er. Harsh Rathore Jul 23 '19 at 16:13