使用Python删除之前杀死文件进程

时间:2019-05-11 14:18:52

标签: python file jar process

如何在删除文件进程之前将其杀死?我要删除200多个文件,我需要休眠吗?

我具有的删除功能:

    def remove_func(self, temp_url):
        for root, dirs, files in os.walk(temp_url):
            for f in files:
                file_path = os.path.join(root, f)
                try:
                    os.unlink(file_path)
                except PermissionError:
                    pid = subprocess.check_output(['pidof','-s',file_path])
                    os.kill(os.getpgid(pid))
                    # or I put the 'continue' in this exception block if the file is used in other processes 
            for d in dirs:
                if os.path.isdir(os.path.join(root, d)):
                    try:
                        shutil.rmtree(os.path.join(root, d))
                    except PermissionError:
                        continue

我得到异常:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

对于我来说,未删除的文件的扩展名为.jar.md5

1 个答案:

答案 0 :(得分:0)

因此,似乎是其他进程在后台运行了,导致了此问题:

The process cannot access the file because it is being used by another process:错误。

上面的代码可以正常工作。