Handling ImportError Exception

suggest change

When you use a Python file as a module, you do not always need to check whether a package is installed, but the check is still useful for scripts.

if __name__ == '__main__':
    try:
        import requests
    except ImportError:
        print("To use this module you need 'requests' module")
        t = input('Install requests? y/n: ')
        if t == 'y':
            import pip
            pip.main(['install', 'requests'])
            import requests
            import os
            import sys
        else:
            import os
            import sys
            print('Some functionality may be unavailable.')
else:
    import requests
    import os
    import sys

pip.main is an internal console-script entry point. A package installed this way is not always importable in the same process, and a failed install leaves the following import requests uncaught.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents