1

I have a project a with several versions of main#.py so I organize them into a directory called run. I normally run project a from ./a by calling python run/main1.py. Because main1.py involves imports beyond the top level package, I need to specify sys.path.insert(0, "./") in main1.py.

Now I've created project b which imports main1.py from a. From b\main.py, how do I get main1.py to import a/utils.py specifically?

Requirements:

  1. Project a is a project I worked on long ago so I would like to make limited changes to just its headers. I would like python run/main1.py to work like it currently does.

  2. I may move the projects between different computers so main1.py needs to import utils.py relative to itself. (ie. not importing with absolute path)

  3. I would like the solution to be scalable. b will need to import modules from several other projects structured like a. I feel that expanding the system's PATH variable may just mess things up. Is there a neater solution?

My projects' files are as follows:

  • a
    • run
      • main1.py
    • utils.py
  • b
    • main.py
    • utils.py

in a/run/main1.py:

import sys
sys.path.insert(0, "./")
from utils import hello    # Anyway to specify this to be ../utils.py ?
hello()

in a/utils.py:

def hello():
    print('hello from a')

in b/main.py:

import sys
sys.path.append("../")
from a.run import main1

import utils
utils.hello()

in b/utils.py:

def hello():
    print('hello from b')

This is the current result. I would like the first line to print 'hello from a':

>>> python run/main1.py:
hello from a
>>> cd ../b
>>> python run/main.py:
hello from b           (we want this to be "hello from a")
hello from b
martineau
  • 119,623
  • 25
  • 170
  • 301
matohak
  • 535
  • 4
  • 19
  • Perhaps add a ```main.py``` in the root directory, and use this as the entry point. This way, the working directory is at the very top level and you can import all of the sub modules such as ```a, b etc...``` – Joshua Nixon Sep 26 '19 at 16:43
  • 1
    Or, you can try something like this - https://stackoverflow.com/a/55911452/4180176 – Joshua Nixon Sep 26 '19 at 16:45
  • this seems much neater than sys.path hack. Thanks!!! – matohak Sep 26 '19 at 19:01

0 Answers0