Nicola Coretti
Nicola Coretti

Reputation: 2685

How to get an error message for errno value in python?

I am using the ctypes module to do some ptrace system calls on Linux, which actually works pretty well. But if I get an error I wanna provide some useful information. Therefore I do an get_errno() function call which returns the value of errno, but I didn't found any function or something else which interprets the errno value and gives me an associated error message.

Am I missing something? Is there a ctypes based solution?

Here is my setup:

import logging
from ctypes import get_errno, cdll
from ctypes.util import find_library, errno

# load the c lib
libc = cdll.LoadLibrary(find_library("c"), use_errno=True)
...

Example:

 return_code = libc.ptrace(PTRACE_ATTACH, pid, None, None)
 if return_code == -1:
   errno = get_errno()
   error_msg = # here i wanna provide some information about the error
   logger.error(error_msg)

Upvotes: 6

Views: 5609

Answers (2)

msuchy
msuchy

Reputation: 5447

>>> import errno
>>> import os
>>> os.strerror(errno.ENODEV)
'No such device'

Upvotes: 1

wberry
wberry

Reputation: 19367

This prints ENODEV: No such device.

import errno, os

def error_text(errnumber):
  return '%s: %s' % (errno.errorcode[errnumber], os.strerror(errnumber))

print error_text(errno.ENODEV)

Upvotes: 5

Related Questions