If the imported module does not exist, the Python interpreter will report a importerror error:
>>> Import Somethingtraceback (most recent): File ' <stdin> ', line 1, in <module>import Error:no module named something
Sometimes, two different modules provide the same functionality, such as Stringio and Cstringio , which provide Stringio .
This is because Python is a dynamic language that interprets execution, so Python code runs slowly.
If you want to improve the speed of Python code, the simplest way is to rewrite some key functions in C , which can greatly improve the execution speed.
The same functionality,Stringio is written in pure Python code, while the Cstringio part of the function is written in C , so Cstringio runs faster.
With importerror errors, we often import modules dynamically in Python:
Try: From Cstringio import stringioexcept importerror: from stringio import Stringio
The above code attempts to import from Cstringio first, and if it fails (for example, Cstringio is not installed), try importing from Stringio. This way, if the Cstringio module is present, we will get a faster run, and if Cstringio does not exist, the code will run slower, but it will not affect the normal execution of the code.
The action of the try is to catch the error and execute the except statement when the specified error is caught.
Task
Using import ... as ..., you can also dynamically import modules of different names.
python 2.6/2.7 provides a JSON module, but Python 2.5 and earlier do not have a JSON module, but you can install a simplejson module, The function signatures and functions provided by these two modules are identical.
Try to write the code to import the JSON module, which will work correctly in Python 2.5/2.6/2.7.
-
- ? What's going on?
-
-
Try importing the JSON first, and if it fails, try importing the Simplejson as JSON
Reference code:
Try: import jsonexcept importerror: import Simplejson as Jsonprint json.dumps ({' Python ': 2.7})
Python Dynamic Import Module