简体   繁体   中英

Importing Modules from Python Package without specifying their names

I am trying to import modules in Python dynamically. That means - I have a Python package with modules inside. Without specifying the modules names, I want to keep a dictionary of each module's name to the pointer to this module.

I tried to use the suggestion from this discussion

My directory is:

foo/
    __init__.py
    bar1.py
    bar2.py

the script I use is:

import pkgutil
import foo

for importer, name, ispkg in pkgutil.iter_modules(foo.__path__, foo.__name__ + "."):
    print "Found submodule %s (is a package: %s)" % (name, ispkg)
    module = __import__(name)
    print "Imported", module

The output I get for the first iteration is:

Found submodule foo.bar1 (is a package: False)
Imported <module 'foo' from '/path/to/foo/__init__.pyc'>

So instead of getting my bar1 module using this, I get the foo package with the import.

How can I get the bar1 and bar2 modules?

Other methods are welcome if the use of pkgutil is not right.

From the import documentation :

When the name variable is of the form package.module , normally, the top-level package (the name up till the first dot) is returned, not the module named by name . However, when a non-empty fromlist argument is given, the module named by name is returned.

Also, importing a package seems to be enough in order to use a submodule of that:

anthony@claudia:~$ python
Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join('one', 'two')
'one/two'
>>> 

And, vice-versa, importing a submodule implicitly imports its parent module:

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.tmpfile()
<open file '<tmpfile>', mode 'w+b' at 0x7f565495d4b0>
>>>

Therefore maybe simply importing foo is enough for you.

The formal details of importing are described at length in the documentation .

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