Sunday, October 16, 2016

Clearing up Python Import Confusion

Today I got the familiar Import not found error from Python:

ImportError: No module named mime.multipart

This is complaining about an import here:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

Here's a good way to figure out what went wrong:

Python 2.7.12 (default, Sep 29 2016, 13:30:34)
[GCC 6.2.1 20160916 (Red Hat 6.2.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import email
>>> dir(email)
['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_name', 'base64MIME', 'email', 'importer', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'sys']
>>> dir(email.mime)
['Audio', 'Base', 'Image', 'Message', 'Multipart', 'NonMultipart', 'Text', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
I see from this that I should be importing email.mime.Multipart (not the upper-case M).

But when I try that, it also does not work:

>>> from email.mime.Multipart import MIMEMultipart
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named Multipart

Turns out the problem was my module name, email.py. This caused some conflicts in python. I changed it to status_email.py and now everything works.


No comments:

Post a Comment