Windows上的python权限错误

时间:2017-11-03 05:47:39

标签: python python-3.x

我正在尝试定期下载一些文件,删除旧文件并用新文件替换它们。第一次运行良好,但第二次抛出错误。

def check_update():
    print ('looking for update')
    shutil.rmtree(config.destination)
    shutil.os.mkdir(config.destination)
    threading.Timer(60.0,check_update).start()

    def get_videos():
        response = requests.get(config.api)
        data = response.json()
        files = list()
        l = len(data)
        for i in range(l):
            files.append(data[i]['filename'])
        return files

    def get_newfiles(myfiles):
        for i in range(len(myfiles)):
            url = config.videos+myfiles[i]
            filename = wget.download(url)

    def move_files(myfiles):
        for i in range(len(myfiles)):
            file = myfiles[i]
            shutil.move(config.source_files+file,config.destination)

    def videos():
        files = set(get_videos())
        myfiles = list(files)
        get_newfiles(myfiles)
        move_files(myfiles)

    videos()
    print ("files are updated")
    res = requests.get(config.api)
    data = res.json()
    return data

data = check_update()

这是错误。

 File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
   self.run()
 File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 1182, in run
   self.function(*self.args, **self.kwargs)
 File "tornado.py", line 8, in check_update
   shutil.rmtree(config.destination)
 File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 494, in rmtree
   return _rmtree_unsafe(path, onerror)
 File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 389, in _rmtree_unsafe
   onerror(os.unlink, fullname, sys.exc_info())
 File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 387, in _rmtree_unsafe
   os.unlink(fullname)
permissionError: [WinError 32] The process cannot access the file because it is being used by another process:

我怎样才能克服这个?

1 个答案:

答案 0 :(得分:0)

尝试删除config.destination目录时发生错误。发生这种情况是因为dir本身或其子节点中的一个(或多个)(可能是dir或文件)在另一个进程中打开(也可能是当前一个)。
经常导致这种情况的典型用例:

  • 该目录中已打开 cmd 控制台。只需cd在dir外面并尝试将其删除
  • 正在运行的程序已打开文件

    • 例如,可能是记事本(或 IDE )已打开位于该目录中的源文件。
    • 但是因为看起来你正在使用视频,也许你想检查下载的文件是否有效并在视频播放器中打开它。

    无论如何,关闭该程序将解决问题

  • 这是特定于你的:我不知道wget.download是如何工作的,但如果它没有阻塞(虽然根据代码似乎并非如此)可能是一个视频来自您以前的运行仍在下载,因此它是开放的。关闭 python 进程会做什么(无论等待直到完成还是从任务管理器中删除它)

注意:在搜索原因时,您应该尝试从文件管理器中删除目录(例如 Windows资源管理器),以避免脚本引入的开销。 / p>