Nếu mục tiêu của bạn là hộp thoại sao chép ưa thích, SHFileOperation Chức năng API Windows cung cấp điều đó. gói pywin32 có một ràng buộc python cho nó, ctypes cũng là một tùy chọn (google "SHFileOperation ctypes" cho ví dụ).
Dưới đây là của tôi (thử nghiệm rất nhẹ) ví dụ sử dụng 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): # in Py3 replace basestring with str
src = os.path.abspath(src)
else: # iterable
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, # flags
None,
None))
if not aborted and result != 0:
# Note: raising a WindowsError with correct error code is quite
# difficult due to SHFileOperation historical idiosyncrasies.
# Therefore we simply pass a message.
raise WindowsError('SHFileOperation failed: 0x%08x' % result)
return not aborted
Bạn cũng có thể thực hiện các hoạt động sao chép tương tự trong "chế độ im lặng" (không có hộp thoại, không confirmationsm, không có popup lỗi) nếu bạn thiết lập các cờ ở trên để shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_NOCONFIRMMKDIR.
Xem SHFILEOPSTRUCT để biết chi tiết.
Nguồn
2013-06-01 09:18:25
bạn đã thực sự đúng lúc chuyển file của cùng một tập tin sử dụng cả Python và Windows Explorer? Tôi có một thời gian rất khó tin rằng Python thực sự chậm hơn. –
Có, tôi đã làm một bài kiểm tra bên cạnh. Đó là trên một mạng, vì vậy có lẽ tốc độ mạng đã can thiệp, nhưng làm thế nào để tôi tìm thấy tốc độ truyền của tôi với shutil? – tylerART
Bạn có thể sử dụng 'time.clock()' trong Python để có được thời gian truyền, nhưng bạn phải sử dụng đồng hồ bấm giờ cho thời gian Explorer. Giả định của tôi là cả Python và Explorer thực hiện cùng một thư viện gọi để thực hiện bản sao, nhưng Explorer cảm thấy nhanh hơn vì thanh tiến trình và có thể do một số ước tính thời gian không chính xác mà nó cung cấp cho bạn. Nếu bạn chạy cả hai cùng một lúc và thấy sự khác biệt lớn, đó là khá thú vị! –