问题
I am trying to move multiple large folders (> 10 Gb , > 100 sub folders, > 2000 files ) between network drives. I have tried using shutil.copytree command in python which works fine except that it fails to copy a small percentage (< 1 % of files ) for different reasons.
I believe robocopy is the best option for me as i can create a logfile documenting the transfer process. However as i need to copy > 1000 folders manual work is out of question.
So my question is essentially how can i call robocopy (i.e. command line ) from within a python script making sure that logfile is written in an external file.
I am working on a Windows 7 environment and Linux/Unix is out of question due to organizational restrictions. If someone has any other suggestions to bulk copy so many folders with a lot of flexibility they are welcome.
回答1:
Subproccess allows you to make system calls. This will allow you to call robocopy as you would from the command line.
from subprocess import call
call(["robocopy", "basefolder newfolder /S /LOG:mylogfile"])
回答2:
Use one of the os.exec
family of functions to start any external program:
- http://docs.python.org/2/library/os.html#process-management
Probably you want os.execlp(file, arg0, arg1, ...)
回答3:
Like halfs13 said use subprocess but you might need to format it like so
from subprocess import call
call(["robocopy",'fromdir', 'todir',"/S"])
Or else it may read the source as everything
回答4:
This put me on the right path but I had to comma separate the options, e.g.
from subprocess import call
call(["robocopy", "./", "newfolder/test02", "/S", "/LOG:mylogfile"])
This worked a treat. The "/S" copied all subfolders.
回答5:
cmd = 'robocopy.exe {0} {1} /S'.format(srcDir, destPath)
output = subprocess.run(cmd.split(), capture_output=True, text=True)
print(output.stdout)
The above snippet will do it.
Note: If srcDir
and destPath
has any white space in it, then the cmd.split()
will not work. Instead you need to do the following:
output = subprocess.run(['robocopy.exe',
r'<full src path>',
r'<full dest path>',
'/S'],
capture_output=True,
text=True)
print(output.stdout)
You can read all about subprocess here: https://docs.python.org/3.7/library/subprocess.html
来源:https://stackoverflow.com/questions/13161659/how-can-i-call-robocopy-within-a-python-script-to-bulk-copy-multiple-folders