Python dynamic import module
If the imported module does not exist, the Python interpreter reports the ImportError error:
>>> import somethingTraceback (most recent call last): File "
", line 1, in
ImportError: No module named something
Sometimes, two different modules provide the same functions, suchStringIOAndCStringIOAll provide the StringIO function.
This is because Python is a dynamic language and interpreted and executed, so Python code runs slowly.
To speed up the running of Python code, the simplest method is to rewrite some key functions in C language, which can greatly improve the execution speed.
With the same function, StringIO is written in pure Python code, while some cStringIO functions are written in C, so cStringIO runs faster.
Using ImportError errors, we often use Python to dynamically import modules:
try: from cStringIO import StringIOexcept ImportError: from StringIO import StringIO
The above code first tries to import from cStringIO. If it fails (for example, cStringIO is not installed), then try to import from StringIO. In this way, if the cStringIO module exists, we will get a faster running speed. If the cStringIO module does not exist, the running speed of at most code will be slow, but it will not affect normal code execution.
TryIs used to capture errors and executeExceptStatement.
Task
Using import... as..., you can also dynamically import modules with different names.
Python 2.6/2.7ProvidedJsonModule, but Python 2.5 and earlier versions do not have a json module, but you can installSimplejsonThe two modules provide the same function signature and function.
Try to write and importJsonThe module code can run properly in Python 2.5/2.6/2.7.
-
? No, what should I do?
-
Try to import json first. If it fails, try to import simplejson as json
Reference code:
try: import jsonexcept ImportError: import simplejson as jsonprint json.dumps({'python':2.7})