How to get ImportError on a development machine? (pwd module)

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

try: import pwd do stuff except ImportError: do other stuff 

I want the import to fail, as on the GAE server itself, but the problem is that it does not interrupt in my development window (ubuntu). How to do this if import is not in my own code?

+4
source share
2 answers

Even easier than messing with __import__ , it's just inserting None into 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 
+7
source

As part of the testing, before you import docutils, you can perform this configuration 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 the stall mode they put things back to normal:

 __builtin__.__import__ = self.savimport 

Explanation: all import operations go through __builtin__.__import__ , and you can reassign this name so that such operations use your own code (alternatives such as import capture are better for purposes such as importing from sources other than the file system, but for such as yours, overriding __builtin__.__import__ , as you see above, gives really simple code).

+4
source

Source: https://habr.com/ru/post/1301200/


All Articles