Python 如果无法使用shututil连接到计算机,如何给出错误信息

Python 如果无法使用shututil连接到计算机,如何给出错误信息,python,Python,在我的程序中,我使用shutil将文件复制到列表中的多台计算机上。我想知道,如果其中一台计算机碰巧被关闭,给出错误并转到下一台计算机的最佳方式是什么 我的原始代码: def copyfiles(servername): # copy config to remote server source = os.listdir("C:/Users/myname/Desktop/PythonUpdate/") # directory where original configs are l

在我的程序中,我使用shutil将文件复制到列表中的多台计算机上。我想知道,如果其中一台计算机碰巧被关闭,给出错误并转到下一台计算机的最佳方式是什么

我的原始代码:

def copyfiles(servername):
    # copy config to remote server
    source = os.listdir("C:/Users/myname/Desktop/PythonUpdate/") # directory where original configs are located
    destination = '//' + servername + '/c$/test/' # destination server directory
    for files in source:
        if files.endswith(".config"):
            shutil.copy(files,destination)

os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("C:/Users/myname/Desktop/PythonUpdate/serverlist.txt", "r") as f:
    for servername in f:


        copyfiles(servername.strip())
我想做的是:

def copyfiles(servername):
    # copy config to remote server
    source = os.listdir("C:/Users/myname/Desktop/PythonUpdate/") # directory where original configs are located
    destination = '//' + servername + '/c$/test/' # destination server directory
    for files in source:
        if files.endswith(".config"):
            try:
                shutil.copy(files,destination)
            except:
                print (" //////////////////////////////////////////")
                print (" Cannot connect to " + servername + ".")
                print (" //////////////////////////////////////////")

os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("C:/Users/myname/Desktop/PythonUpdate/serverlist.txt", "r") as f:
    for servername in f:


        copyfiles(servername.strip())

当你使用试块的想法是正确的时,你应该更确切地知道你认为哪些条件是可以原谅的。例如,如果您以某种方式获得了or,您将不想继续

作为第一步,您应该只使用陷阱,因为这是用来指示各种读/写错误(至少 这就是文档所说的)。根据,您的错误很可能是a(它是
OSError
的子类):

如果异常可能有其他原因,可以通过使用else子句的扩展形式测试错误对象本身来进一步缩小确切原因。例如,
WindowsError
具有一个属性,该属性包含异常的系统级错误代码。您可能希望原谅的可能候选人:

  • (53)
  • (54)
  • (55)
  • (57)
  • (59)
  • (64)
  • (70)
  • (88)
您的代码可以如下所示:

try:
    shutil.copy(files, destination)
except WindowsError as ex:
    if ex.winerror in (53, 54, 55, 57, 59, 64, 70, 88):
        print('...')
    else:
        raise
您可能还需要检查异常的属性。这将告诉您预期的文件是否导致了此异常。此检查与
winerror
上的检查无关,可以与上面显示的检查一起进行,也可以排除:

try:
    shutil.copy(files, destination)
except WindowsError as ex:
    if ex.filename2.startswith('//' + filename2):
        print('...')
    else:
        raise

您的函数只处理复制到单个网络目标的操作,因此,如果
shutil
失败,则无需继续。对不起,我忘了发布其他代码。我修复了它。像这样使用裸露的
except:
语句是一种糟糕的编程实践,因为它可以隐藏各种不相关的异常。更具体一点。@martineau。我想这正是OP所要问的。也许有答案?是的,我想知道如何提高自己。
try:
    shutil.copy(files, destination)
except WindowsError as ex:
    if ex.filename2.startswith('//' + filename2):
        print('...')
    else:
        raise