C有perror和errno,它打印并存储遇到的最后一个错误。在执行文件io时这很方便,因为我没有fstat()作为fopen()参数失败的每个文件向用户显示调用失败的原因。
我想知道在python中优雅地处理IOError异常时获取errno的正确方法是什么?
In [1]: fp = open("/notthere") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 2] No such file or directory: '/notthere' In [2]: fp = open("test/testfile") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 13] Permission denied: 'test/testfile' In [5]: try: ...: fp = open("nothere") ...: except IOError: ...: print "This failed for some reason..." ...: ...: This failed for some reason...
答案 0 :(得分:30)
Exception有一个errno
属性:
try:
fp = open("nothere")
except IOError as e:
print(e.errno)
print(e)
答案 1 :(得分:26)
这是你如何做到的。另请参阅errno
模块和os.strerror
函数以了解某些实用程序。
import os, errno
try:
f = open('asdfasdf', 'r')
except IOError as ioex:
print 'errno:', ioex.errno
print 'err code:', errno.errorcode[ioex.errno]
print 'err message:', os.strerror(ioex.errno)
有关IOError属性的更多信息,请参阅基类EnvironmentError:
答案 2 :(得分:21)
try:
fp = open("nothere")
except IOError as err:
print err.errno
print err.strerror
答案 3 :(得分:2)
除了'之外,还可以测试不同的例外情况。条款,例如
try:
serial_port.open()
except (AttributeError, SerialException) as e:
print('cannot open serial port: {}'.format(e))