如何让python等待一个正在进行的过程完成

问题描述

我正在编写一个 Python 脚本来将文件夹中的文件组织到相应的目录中。我希望它连续运行,所以我使用 while 循环来扫描文件。但是如果我尝试在文件夹中粘贴一个文件,我的脚本就会终止说 The process cannot access the file because it is being used by another process。我知道它因为粘贴文件的过程而停止。现在我希望我的脚本等到正在进行的过程停止

代码示例:

while(True):
    scan()
    #rest of commands

所以我希望 scan() 函数等到进程结束

提前致谢

解决方法

使用 try/except 语句。如果 scan() 函数以错误结束,则打印一些消息并继续尝试。您也可以pass 例外并继续。代码应该是这样的:

while(True):
    try:
        scan()
        #rest of commands
    except:
        # error message or pass