做shutil.rmtree时出错

时间:2015-07-22 13:35:07

标签: python python-2.7 shutil

在我的python代码中,我将一些安装程序复制到temp并安装它然后我想删除临时副本。 我正在使用“shutil.rmtree”函数删除temp中的安装程序副本。 有时我收到错误,如“[错误32]该进程无法访问该文件,因为它正被另一个进程使用”

我该如何避免?我们有办法检查任何其他程序没有使用的目录吗?如果是,我们可以检查目录的可用性,直到另一个进程离开控制并删除它?

请帮我提供示例代码!我对python很新。

copy_dst = tempfile.mkdtemp()

if success:
    success = robocopy_file_or_folder(installer_location, copy_dst)

local_path_to_setup = os.path.join(copy_dst, app_folder, 'setup.exe')

if success:
    success, response_text = install_product(local_path_to_setup, success, response_text)
try:
    if success:
        shutil.rmtree(copy_dst, ignore_errors = False, onerror=handle_remove_readonly)
except OSError as e:
    log("      %s\n      Delete installer Local Copy at \"%s\" failed.\n" % (e, copy_dst))
    success = False

这是代码!!并且“install_product()”将通过在另一个命令中调用setup.exe来安装产品.robocopy_file_or_folder() - 将复制文件。

def handle_remove_readonly(func, path, exc):
"""
Changes the access mode of the specified folder to remove read_only
"""
exc_value = exc[1]
if func in (os.rmdir, os.remove) and exc_value.errno == errno.EACCES:
    os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
    func(path)
else:
    raise

1 个答案:

答案 0 :(得分:0)

  

install_product()”将通过调用另一个command.robocopy_file_or_folder()中的setup.exe来安装产品 - 将复制文件。

等待安装完成,并在尝试删除目录之前退出setup.exe