在python中重命名文件会导致设备或资源繁忙

时间:2018-04-04 08:24:21

标签: python linux

我正在用python编写脚本。

首先,让我告诉你例外:

Traceback (most recent call last):

File "/home/jiewei/PycharmProjects/TestEngine/test/test_multiple_classes.py", line 23, in test_create_symlink_and_run_test_in_devbench_but_is_called_in_vdi
    self.sm.make_backups(self.dev_path)
File "testengine/SymlinkManger.py", line 24, in make_backups
    self.make_backup(file_path)
File "testengine/SymlinkManger.py", line 19, in make_backup
    os.rename(file_path, new_name)
OSError: [Errno 16] Device or resource busy

然后是导致问题的方法:

def make_backup(self, file_path):
    name = os.path.basename(file_path)
    folder_path = os.path.dirname(file_path)
    if not name.startswith('backup_'):
        new_name = os.path.join(folder_path,"backup_"+name)
        os.rename(file_path, new_name)

def make_backups(self, folder_path):
    for file in folder_path:
        file_path = os.path.join(folder_path, file)
        self.make_backup(file_path)    

我是否需要创建线程来解决此问题?我猜原因是os被多个进程使用,这导致异常。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你绝对需要线程来解决这个问题。它只是让你重新命名一些实际使用的东西......

查看Linux manpage for the rename() call,重命名正在使用的目录时,您可能会收到EBUSY(错误16):

  

重命名失败,因为oldpath或newpath是一个目录   由某个进程使用(可能作为当前工作目录,或作为root用户)   目录,或因为它是开放的阅读)或正在使用   系统(例如作为安装点),而系统考虑这一点   一个错误。 (注意,没有要求返回EBUSY   案例 - 无论如何重命名都没有错 - 但确实如此   如果系统无法以其他方式处理,则允许返回EBUSY   的情况。)