简体   繁体   中英

Can't find module that exists

From the cli I enter the python shell via python .

I then take a look at my import search path:

import sys
print '\n'.join(sys.path)

/path/to/a/package/foo.bar
/other paths...

So I know foo.bar is in my python search path.

Continuing inside the python shell:

import imp
imp.find_module('foo.bar')

ImportError: No module named foo.bar

Hmm, the sys.path tells me that foo.bar is on the python search path, but the imp module can't seem to find it.

Continuing further inside the python shell:

from foo.bar import baz
baz

<module 'foo.bar.baz' from '/path/to/a/package/foo.bar/foo/bar/baz.pyc'>

Yes, I have directories foo and bar under my main directory foo.bar . Why would imp.find_module not be able to locate my package?

imp.find_module does not handle names with dots. From the documentation :

This function does not handle hierarchical module names (names containing dots).

It also points out a solution:

In order to find PM, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__ . When P itself has a dotted name, apply this recipe recursively.

  • Don't have a . in the folder name.
  • Make sure there is an empty __init__.py file in the foo & bar folders. This is required for python to see it as a package
  • Make sure the folder that the foo folder is in, is in sys.path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM