how to get only the module name ModuleNotFoundError

How only to print the module name with ModuleNotFoundError arguments in python.

my code:

try:
    import requests
except ModuleNotFoundError as error1:
    print(error1)

In this case I am getting output as below:

No module named ‘requests’

I want to be printed only the name of the module that met the exception.

output I need:

‘requests’

Regards,
Vishnu

>Solution :

The module name in an ModuleNotFoundError is accessed by the variable name

try:
    import this_module_doesnt_exist
except ModuleNotFoundError as error1:
    print(error1.name)

Output:

this_module_doesnt_exist

Leave a Reply