![]() |
Importing module from a package results in import error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Importing module from a package results in import error (/thread-25352.html) |
Importing module from a package results in import error - goghvv - Mar-27-2020 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: 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? RE: Importing module from a package results in import error - Malt - Mar-27-2020 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 RE: Importing module from a package results in import error - goghvv - Mar-27-2020 (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. |