How to force an ImportError on development machine? (pwd module)

后端 未结 2 1467
我在风中等你
我在风中等你 2020-12-11 20:19

I\'m trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):

try:
    import pwd
    do stuff
except         


        
相关标签:
2条回答
  • 2020-12-11 20:43

    Even easier than messing with __import__ is just inserting None in the sys.modules dict:

    >>> import sys
    >>> sys.modules['pwd'] = None
    >>> import pwd
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named pwd
    
    0 讨论(0)
  • 2020-12-11 21:01

    In your testing framework, before you cause docutils to be imported, you can perform this setup task:

    import __builtin__
    self.savimport = __builtin__.__import__
    def myimport(name, *a):
      if name=='pwd': raise ImportError
      return self.savimport(name, *a)
    __builtin__.__import__ = myimport
    

    and of course in teardown put things back to normal:

    __builtin__.__import__ = self.savimport
    

    Explanation: all import operations go through __builtin__.__import__, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding __builtin__.__import__, as you see above, affords truly simple code).

    0 讨论(0)
提交回复
热议问题