How can i call robocopy within a python script to bulk copy multiple folders?

回眸只為那壹抹淺笑 提交于 2019-12-23 03:30:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!