Access to errno from Python?

前端 未结 6 1325
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 05:00

I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls

6条回答
  •  轮回少年
    2020-12-29 05:38

    Here is a snippet of code that allows to access errno:

    from ctypes import *
    
    libc = CDLL("libc.so.6")
    
    get_errno_loc = libc.__errno_location
    get_errno_loc.restype = POINTER(c_int)
    
    def errcheck(ret, func, args):
        if ret == -1:
            e = get_errno_loc()[0]
            raise OSError(e)
        return ret
    
    copen = libc.open
    copen.errcheck = errcheck
    
    print copen("nosuchfile", 0)
    

    The important thing is that you check errno as soon as possible after your function call, otherwise it may already be overwritten.

提交回复
热议问题