如果你的目标是一个漂亮的复制对话框,Windows API函数
SHFileOperation可以实现。pywin32包有它的Python绑定,ctypes也是一个选择(搜索“SHFileOperation ctypes”可以找到示例)。
以下是我使用pywin32编写的(经过轻微测试的)示例:
import os.path
from win32com.shell import shell, shellcon
def win32_shellcopy(src, dest):
"""
Copy files and directories using Windows shell.
:param src: Path or a list of paths to copy. Filename portion of a path
(but not directory portion) can contain wildcards ``*`` and
``?``.
:param dst: destination directory.
:returns: ``True`` if the operation completed successfully,
``False`` if it was aborted by user (completed partially).
:raises: ``WindowsError`` if anything went wrong. Typically, when source
file was not found.
.. seealso:
`SHFileperation on MSDN <http://msdn.microsoft.com/en-us/library/windows/desktop/bb762164(v=vs.85).aspx>`
"""
if isinstance(src, basestring):
src = os.path.abspath(src)
else:
src = '\0'.join(os.path.abspath(path) for path in src)
result, aborted = shell.SHFileOperation((
0,
shellcon.FO_COPY,
src,
os.path.abspath(dest),
shellcon.FOF_NOCONFIRMMKDIR,
None,
None))
if not aborted and result != 0:
raise WindowsError('SHFileOperation failed: 0x%08x' % result)
return not aborted
如果您将上面的标志设置为shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_NOCONFIRMMKDIR
,您也可以在“静默模式”(无对话框、无确认窗口、无错误弹出窗口)下执行相同的复制操作。有关详细信息,请参见SHFILEOPSTRUCT。
time.clock()
来获取传输时间,但是你需要使用秒表来计时Explorer。我的假设是Python和Explorer都会调用相同的库来执行复制操作,但是Explorer感觉更快,因为它有进度条,也许还因为它给出了一些不正确的时间估计。如果你同时运行两个程序并看到巨大的差异,那就非常有趣了! - Nathaniel Waisbrot