Simulating lack of a dependency when testing a python script
What's the best way to temporarily hide an installed module from a python s开发者_开发技巧cript to test how it handles environments that don't have the module installed?
I'd like to avoid having to uninstall the module just to test.
import sys
sys.modules['numpy']=None
Setting sys.modules['numpy']=None
makes Python think that it has already tried and failed to import numpy
. Subsequent attempts at importing numpy
now raise ImportError
:
try:
import numpy
except ImportError as err:
print(err)
# No module named numpy
Deleting sys.modules['numpy']
allows numpy
to be imported as normal:
del sys.modules['numpy']
import numpy
Change your Python Path.
The order of directories in sys.path
shows the order of a search.
You can change sys.path
in a test to alter the search order.
精彩评论