Python Forum

Full Version: Importing module from a package results in import error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
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?
If you want to run your program from /home/pkg then you can actually make a call to change your directory path to /home/pkg using os.chdir() in client.py
(Mar-27-2020, 06:42 PM)Malt Wrote: [ -> ]If you want to run your program from /home/pkg then you can actually make a call to change your directory path to /home/pkg using os.chdir() in client.py

I don't want to force the client into doing that.