简体   繁体   中英

transitive dynamic imports in python using the imp module

I'm using the imp module to dynamically import a Python module. Works great.

But a colleague of mine wanted to refactor some of the module into another module in the same directory, and this breaks things. How do I get this to work? I'm passing the right path into find_module ; the dynamic import to bar works fine, but when bar tries to pull in baz from the same directory, it fails. Source code reproduced below and on github .

C:\tmp\git\python-imp-bug>cd a

C:\tmp\git\python-imp-bug\a>python foo.py
Traceback (most recent call last):
  File "foo.py", line 7, in <module>
    m = find_and_load('bar',['../b'])
  File "foo.py", line 5, in find_and_load
    return imp.load_module(module, file, pathname, description)
  File "../b\bar.py", line 1, in <module>
    import baz
ImportError: No module named baz

a/foo.py:

import imp

def find_and_load(module, path):
    file, pathname, description = imp.find_module(module, path)
    return imp.load_module(module, file, pathname, description)

m = find_and_load('bar',['../b'])

b/bar.py:

import baz

def tweedledee():
    return 42

b/baz.py:

def tweedledum():
    return 24

Grumble. Found a temporary workaround by modifying sys.path, though I don't like it. It seems like there should be a way to do this without messing with sys.path. I tried catching ImportError but it just contains a string and not the name of the module that was attempted to import (yeah, I can parse that string, but that's just totally wrong)

a/foo.py:

import imp
import sys

def find_and_load(module, path):
    file, pathname, description = imp.find_module(module, path)
    try:
        n = len(sys.path)
        sys.path += path
        return imp.load_module(module, file, pathname, description)
    finally:
        del sys.path[n:]
        file.close()

m = find_and_load('bar',['../b'])
print m.tweedledee() + m.tweedledum()

b/bar.py:

import baz

def tweedledee():
    return 42

tweedledum = baz.tweedledum

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