TobyTobyo
TobyTobyo

Reputation: 405

Python folder copying issue

I'm trying to copy a directory from a portable drive to the main disk using the following lines:

temp_command = "xcopy " + new_dir + " " + basedir + "/Libraries/Installed" #This isn't working. Raises error.
    if subprocess.check_output(temp_command) == True: # copy file to local directory on C:

And I get this error:

Invalid number of parameters
Traceback (most recent call last):
  File "E:/Jason Core/Boot.py", line 103, in <module>
    control()
  File "E:/Jason Core/Boot.py", line 96, in control
    install_libs()
  File "E:/Jason Core/Boot.py", line 45, in install_libs
    if subprocess.check_output(temp_command) == True: # copy file to local directory on C:
  File "C:\Python27\lib\subprocess.py", line 574, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'xcopy c:/Downloads/Python_Libraries E:/Libraries/Installed' returned non-zero exit status 4

Any suggestions on what I can change here?

Upvotes: 0

Views: 670

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

You're using check_output in a wrong way.

check_output returns the output of the command, not True or False, but only if the command succeeded, which isn't the case here.

Now why isn't it succeeding?

Reasons are multiple, but the most obvious one is that

xcopy c:/Downloads/Python_Libraries E:/Libraries/Installed

won't work even if the input exists & output can be written, because you're passing names with slashes to xcopy, which is an old MS-DOS like command which interprets that as switches.

The proper command would have been:

subprocess.check_output([r"xcopy",r"c:\Download\Python_Libraries",r"E:\Libraries\Installed"])

(note the raw prefix to avoid backslashes being interpreted by python and passing a list of parameters so if there are spaces in paths, quoting is handled automatically)

That way of running subprocess.check_output is the right one in the general case, but in this simple case you'd be better off with

import shutil
shutil.copytree(r"c:\Download\Python_Libraries",r"E:\Libraries\Installed")

(no need to run a command to copy files/dirs, python comes with batteries included, as they say: if you get an error there it will be easier to understand it)

Upvotes: 2

Related Questions