-1

I'm using Python 3.8.3 on Windows 10. I have the following code:

import # all the necessary modules

try:
    # do something
except WebDriverException:
    print(sys.exc_info()[0])

Upon the exception, I receive the following:

<class 'selenium.common.exceptions.SessionNotCreatedException'>

How do I get print() to output only the string within <class>?:

selenium.common.exceptions.SessionNotCreatedException

Any help would be appreciated.

howdoicode
  • 779
  • 8
  • 16
  • `except WebDriverException as exc: print(type(exc))`? – jonrsharpe Jul 24 '20 at 16:08
  • @jonrsharpe That prints out the same exact thing as `print(sys.exc_info()[0])`. I'm looking to only out put the string after . – howdoicode Jul 24 '20 at 16:31
  • `.__name__`? See https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance – jonrsharpe Jul 24 '20 at 16:31
  • @jonrsharpe I tried that as well. The first answer below, was modified with `__name__`, but it only gives `SessionNotCreatedException`. Which is close, but not the exact string. – howdoicode Jul 24 '20 at 16:33
  • Then see e.g. https://stackoverflow.com/q/2020014/3001761 - what's the *context* here, what are you using that for, and what research have you done already? – jonrsharpe Jul 24 '20 at 16:42
  • @jonrsharpe I've done searches and tried several answers from various threads on here and websites. Unfortunately I didn't find the solution. That's why I asked my specific question. – howdoicode Jul 24 '20 at 16:53
  • Please [edit] the question to *show your research*, then - if you've tried `__name__`, `__qualname__` etc. then include that information. [Sharing your research helps everyone.](https://stackoverflow.com/help/how-to-ask) – jonrsharpe Jul 24 '20 at 16:55
  • @jonrsharpe. I've modified the duplicate – Mad Physicist Feb 09 '21 at 21:18

2 Answers2

1

To get the full path of an exception, use the inspect.getmodule method to get the package name and use type(..).__name __ to get the class name.

except WebDriverException as ex: 
    print (type(ex).__name__)

For the full name, try

import inspect
.....
print(inspect.getmodule(ex).__name__, type(ex).__name__, sep='.')

To keep it simple, you can just parse the string you already have

print(str(sys.exc_info()[0])[8:-2]) # selenium.common.exceptions.SessionNotCreatedException
Mike67
  • 11,175
  • 2
  • 7
  • 15
-1

Maybe you can try this

import # anything

try:
   # something
except Exception as e:
   print(e)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lalit Vavdara
  • 406
  • 4
  • 9
  • I tried this from the first answer. As I commented there, this produces the same output as `sys.exc_info()[1]`, not the string I'm looking for in my question. – howdoicode Jul 24 '20 at 16:27