Nested Software
Nested Software

Reputation: 313

Cannot import a module in parent directory

I am trying to get a python project working in Ubuntu 17, but I'm having trouble with module loading. I've been able to isolate the problem with a trivial example. This example works in Windows 10, but not in Ubuntu. Help getting this to work would be greatly appreciated!

Here are the steps I am following:

First I create a project directory called code_playground in ~/dev. Next I create a virtualenv for this project:

~/dev$ which virtualenv
/usr/local/bin/virtualenv

~/dev$ virtualenv -p python3.6 code_playground/
Running virtualenv with interpreter /usr/bin/python3.6
Using base prefix '/usr'
New python executable in /home/user/dev/code_playground/bin/python3.6
Also creating executable in /home/user/dev/code_playground/bin/python
Installing setuptools, pip, wheel...done.

I activate the virtual environment:

~/dev/code_playground$ source ./bin/activate
(code_playground) ~/dev/code_playground$ 

It seems to work:

(code_playground) ~/dev/code_playground$ which python
/home/user/dev/code_playground/bin/python

I create a file called mod_a.py with a simple function in it:

def print_name(name):
    print('Your name is {0}'.format(name))

Now I create a subdirectory called sub :

(code playground) ~/dev/code_playground$ mkdir sub
(code playground) ~/dev/code_playground$ cd sub
(code playground) ~/dev/code_playground/sub$ 

Inside sub, I create a file called mod_b.py with these contents:

from mod_a import print_name

print_name('Joe')

I try to run mod_b.py, but I get an error:

(code playground) ~/dev/code_playground/sub$ python mod_b.py 
Traceback (most recent call last):
   File "mod_b.py", line 1, in <module>
      from mod_a import print_name
ImportError: No module named mod_a

Upvotes: 0

Views: 1377

Answers (1)

user1785721
user1785721

Reputation:

The Python interpreter has to know where to find module_a.py. The fact that the file that is importing the module module_a.py is in a sub-directory for the directory where module_a.py exist, "is not a thing that help much". You can try few things:

1- Add your mod_a.py path (before the script run) to your Python's path as suggested by @CristiFati.

2- Add your mod_a.py path (using Python code) to your Python's path doing something like (nasty one):

import
sys.path.insert(0, '/home/user/dev/code_playground/bin/python')
from mod_a import print_name
...

3- Evaluate relative imports (6.4.2. Intra-package References)

Upvotes: 1

Related Questions