Dynamic Import module in Python

Source: Internet
Author: User

When the imported module does not exist, it will be reported importerror error, in order to avoid this error can be alternative to other modules or to prefer to use a module or package, you can use the try...except ... How the module or package is imported.

For example:

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 can be run correctly in Python 2.5/2.6/2.7

Try:    import jsonexcept importerror:    import Simplejson as Jsonprint json.dumps ({' Python ': 2.7})

Try importing the JSON first, and if it fails, try importing the Simplejson as JSON.

Dynamic Import module in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.