获取错误的错误号

fix*_*xer 11 python error-handling paramiko

我需要从Python中发生的错误中获取错误号.

防爆; 尝试通过Paramiko包传输目录时,这段代码会出现错误:

try:
    sftp.put(local_path,target_path)    
except (IOError,OSError),errno:
    print "Error:",errno
Run Code Online (Sandbox Code Playgroud)

我得到了输出,

Error: [Errno 21] Is a directory
Run Code Online (Sandbox Code Playgroud)

我想利用错误号进入更多代码来传输目录和目录内容.

Tim*_*ker 14

谢谢你澄清了你的问题.

ExceptionPython中的大多数都没有"错误号".一个例外(没有双关语意)是HTTPError例外,例如:

import urllib2 
try:
   page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
   if err.code == 404:
       print "Page not found!"
   else:
       ...
Run Code Online (Sandbox Code Playgroud)

另一个例外(如bobince所述)是EnvironmentError:

import os
try:
   f=open("hello")
except IOError, err:
   print err
   print err.errno
   print err.strerror
   print err.filename
Run Code Online (Sandbox Code Playgroud)

输出

[Errno 2] No such file or directory: 'hello'
2
No such file or directory
hello
Run Code Online (Sandbox Code Playgroud)