【发布时间】:2014-09-24 17:21:28
【问题描述】:
这个问题与python没有直接关系,但我需要windows下python32下的工作实现。
从这个answer开始我假设在windows下使用shutil.rmtree()是真的很慢(我需要删除超过3M的文件,每天需要超过24小时)所以我想要使用subprocess.call() 和rmdir,但由于我的%PATH% 系统变量中有cygwin 错误rmdir 被调用,我会得到这个:
>>> args = ['rmdir', r'D:\tmp']
>>> subprocess.call(args)
cygwin warning:
MS-DOS style path detected: D:\tmp
Preferred POSIX equivalent is: /cygdrive/d/tmp
CYGWIN environment variable option "nodosfilewarning" turns off this warning.
Consult the user's guide for more details about POSIX paths:
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
rmdir: failed to remove `D:\\tmp': Directory not empty
1
注意:我知道递归删除文件夹需要使用/S /Q。
我怎样才能确保调用正确的rmdir(就像在linux下你会使用绝对路径-/bin/rm)最好不使用使用shell=True?
是否有替代实用程序(例如使用robocopy /MIR)?
编辑:速度比较
我测试了使用Measure-Command删除1,257,449 个文件,750,251 个文件夹中的 237 GB(255,007,568,228 字节)的不同方法。
+-------------------+-------------+----------+-----------------+
| | rmdir /s /q | shutil | SHFileOperation |
+-------------------+-------------+----------+-----------------+
| Hours | 3 | 5 | 6 |
| Minutes | 26 | 52 | 14 |
| Seconds | 46 | 13 | 48 |
| TotalMinutes | 207 | 352 | 375 |
| TotalSeconds | 12406 | 21134 | 22488 |
| TotalMilliseconds | 12406040 | 21133805 | 22488436 |
+-------------------+-------------+----------+-----------------+
注意:测试是在生产服务器上运行的(因此结果可能会受到影响)
【问题讨论】:
-
如果你的路径中有 cygwin,你总是可以使用
rm -rf。 -
您遇到的错误似乎与目录不为空有关。如果其中有文件,Windows 将抛出此错误。添加
/s开关使其递归? -
@FatalError 不幸的是,脚本将在多台机器上运行,我不能依赖它们来安装 cygwin(我可以检查 cygwin 并调用 cygwin 等等,但我想要一个优雅的和简单的解决方案)
-
@Tadgh 在这种情况下我并不真正关心,因为重点是无效的
rmdir(来自cygwin)被调用,我不想构建代码这取决于没有人会在进程的cwd中创建文件rmdir.exe。 -
"我认为使用 shutil.rmtree() 真的很慢" - 你是这样认为的,还是你测量过的?