I'm currently using shutil.copy2()
to copy a large number of image files and folders (anywhere between 0.5 and 5 gigs). Shutil
works fine, but it's so slow. I'm wondering if there is a way to pass this info over to Windows to make the copy and give me its standard transfer dialog box. You know, this guy...
Many times, my script will take about twice the time the standard windows copy takes, and it makes me nervous that my python interpreter hangs while running the copy. I run the copy process multiple times and I'm looking to cut the time down.
If your goal is a fancy copy dialog, SHFileOperation Windows API function provides that. pywin32 package has a python binding for it, ctypes is also an option (google "SHFileOperation ctypes" for examples).
Here is my (very lightly tested) example using 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
You can also perform the same copy operation in "silent mode" (no dialog, no confirmationsm, no error popups) if you set the flags above to shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_NOCONFIRMMKDIR.
See SHFILEOPSTRUCT for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With