Search code examples
pythonlinuxpython-2.7virtualenvmako

Python import error "No module named template"


Using virtualenv, got it working [I think], but not having any luck trying to import modules. In a file makotest.py, I have:

    from mako.template import Template

located in my home folder, virtualenv in folder: venv

installed mako just fine, pip freeze:

    Mako==1.0.0
    MarkupSafe==0.23
    argparse==1.2.1
    wsgiref==0.1.2

in the shell, I see the (venv) so it should be working right? I ran a syspath with it activated and got:

    '/home/username'
    '/home/username/venv/lib/python2.7'
    '/home/username/venv/lib/python2.7/plat-x86_64-linux-gnu'
    '/home/username/venv/lib/python2.7/lib-tk'
    '/home/username/venv/lib/python2.7/lib-old'
    '/home/username/venv/lib/python2.7/lib-dynload'
    '/usr/lib/python2.7'
    '/usr/lib/python2.7/plat-x86_64-linux-gnu'
    '/usr/lib/python2.7/lib-tk'
    '/home/username/venv/local/lib/python2.7/site-packages'
    '/home/username/venv/lib/python2.7/site-packages' 

and within that site-packages folder, is a 'mako' folder with a template.py/pyc as well as the init file.

But every time I run 'python makotest.py', I get the import error. Totally out of ideas, help please~


update with traceback:

Traceback (most recent call last):
  File "makotest.py", line 1, in <module>
    from mako.template import *
  File "/home/username/venv/makotest.py", line 1, in <module>
    from mako.template import *
ImportError: No module named template

Solution

  • Your question lacked the full python traceback so I can only answer this based on my understanding.

    The fact that your cwd (and thus pythonpath) contains a mako.py file is where you're getting tripped up. Try renaming it, and removing the mako.pyc in your home dir first, then re-running this.

    Basically python is trying to import from your mako.py file rather than the mako.py directory in your site-packages.

    See my example below:

        -bash-4.1$ bin/pip freeze
        #...
        mock==1.0.1
        #..
        -bash-4.1$ bin/python
        Python 2.7.3 (default, Apr 10 2013, 09:39:41)
        [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>> from mock import patch
        in mock.py
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          File "mock.py", line 3, in <module>
            from mock import patch
        ImportError: cannot import name patch
        >>>
        -bash-4.1$ mv mock.py mock2.py
        -bash-4.1$ rm mock.pyc
        -bash-4.1$ bin/python
        Python 2.7.3 (default, Apr 10 2013, 09:39:41)
        [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>> from mock import patch
        >>> patch
        <function patch at 0x7f8276a4a7d0>