I have a python project which needs to be able to run external scripts.
These scripts are dynamically imported in a directory structure with several modules.
Now, as these scripts are written independently and are unaware of each other, they often use the same modules names.
This makes it problematic for me when importing them one after the other.
For example, here's my directory structure:
- main.py
- a
- a.py
- utils.py
- b
- b.py
- utils.py
- a
So I have a main.py script in the root folder and 2 "external" scripts in a and b folders.
Both scripts use a different utils.py module.
Contents of a/a.py:
import utils
utils.hello()
Contents of a/utils.py:
def hello():
print 'hello from a'
Contents of b/b.py:
import utils
utils.hello()
Contents of b/utils.py:
def hello():
print 'hello from b'
Contents of main.py
import sys
sys.path.append('a')
import a
sys.path.append('b')
import b
Now, this example prints:
hello from a
hello from a
And I obviously need it to print:
hello from a
hello from b
As I'm not in-charge of the "external" scripts and I cannot modify them, is there any way I can accomplish this?
edit
Using @moinuddin-quadri answer of importing like: from a import a indeed works for this easy example, but what about this:
- main.py
- a
- a.py
- lib
- utils.py
- lib2
- utils2.py
- b
- b.py
- lib
- utils.py
- lib2
- utils2.py
- a
Where each utils.py is doing:
from lib2 import utils2
For this to work I need the root script folder to be on sys.path
When b/lib/utils tries to run: from lib2 import utils2, it receives the utils2 in a/lib2