Mar-27-2020, 06:18 PM
I have a folder 'home', containing another folder (package) that contains couple python files (modules).
--- home
------ pkg
--------- mod1.py
--------- mod2.py
Inside mod1.py, I am importing mod2.py:
mod1.py:
--- home
------ pkg
--------- mod1.py
--------- mod2.py
--------- client.py
client.py:
--- home
------ pkg
--------- mod1.py
--------- mod2.py
------ client.py
client.py:
I want the client.py to be able to run from wherever, and for 'mod1' to be able to import 'mod2' regardless of what's the current working directory is.
Is it possible?
--- home
------ pkg
--------- mod1.py
--------- mod2.py
Inside mod1.py, I am importing mod2.py:
mod1.py:
import mod2 # use symbols from mod2 ...Now, suppose I create, inside 'pkg', a 'client' code that wants to import (and use) symbols from mod1.py
--- home
------ pkg
--------- mod1.py
--------- mod2.py
--------- client.py
client.py:
#!/usr/local/bin/python3 import mod1 # use symbols from mod1 ...That all works fine, but watch what happens when the client is importing mod1 from outside 'pkg':
--- home
------ pkg
--------- mod1.py
--------- mod2.py
------ client.py
client.py:
#!/usr/local/bin/python3 import pkg.mod1 # use symbols from mod1 ...I get the following:
Output:Traceback (most recent call last):
File "./client.py", line 2, in <module>
import pkg.mod1
File "/home/pkg/mod1.py", line 1, in <module>
import mod2
ModuleNotFoundError: No module named 'mod2'
Now, I understand that the current working directory for client.py has changed from '/home/pkg/' to '/home/' and that python is searching for 'mod2' at '/home/' instead of at '/home/pkg/', but how can I overcome that?I want the client.py to be able to run from wherever, and for 'mod1' to be able to import 'mod2' regardless of what's the current working directory is.
Is it possible?