Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: module in same directory as script: "ImportError: No module named"

I'm trying to import a module (venues) from an IPython shell. The venues module is correctly imported but it then tries itself to import a module named makesoup and fails to do so.

I'm located in the ~ directory and am trying to import the venues.py file located in the subdirectory processors. The makesoup.pyfile is also located in the processors subdirectory, which means any Python script near it should be able to find it, right?

In [1]: import processors.venues --------------------------------------------------------------------------- ImportError                               Traceback (most recent call last) <ipython-input-1-765135ed9288> in <module>() ----> 1 import processors.venues  ~/processors/venues.py in <module>()       7 """       8  ----> 9 import makesoup      10 import re      11   ImportError: No module named 'makesoup' 

I have added an empty __init__.py in both the ~ and processors directories, unsuccessfully.

Note: the makesoup module is correctly imported when I'm located in processors but I know this is not the only way it should work.

like image 954
Arnaud Renaud Avatar asked Dec 08 '14 19:12

Arnaud Renaud


People also ask

How do I fix the ImportError No module named error in Python?

To get rid of this error “ImportError: No module named”, you just need to create __init__.py in the appropriate directory and everything will work fine.

Why can't Python find my module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

What is ImportError in Python?

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.


1 Answers

The makesoup.py file is also located in the processors subdirectory, which means any Python script near it should be able to find it, right?

No. This feature was changed in Python 3 and that syntax no longer works.

Change the import makesoup to this:

from . import makesoup 

Or to this:

from processors import makesoup 

Both of these will make it impossible to run python processors/venues.py directly, though you can still do python -m processors.venues from your home directory.

like image 109
Kevin Avatar answered Sep 18 '22 00:09

Kevin