Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Here's my copy.py:

from subprocess import call
call("copy p2.txt p3.txt")

If in command prompt I use

copy p2.txt p3.txt it copies fine.

but when I use python copy.py it gives me:

Traceback (most recent call last):
  File "copy.py", line 2, in <module>
    call("copy p2.txt p3.txt")
  File "C:\Python27\lib\subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 679, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

If I replace the python call to copy with xcopy, it works fine.

Why would this be?

share|improve this question
add comment

1 Answer 1

When subprocess.call()ing a command like in a shell, you'll need to specify shell=True as well.

from subprocess import call
call("copy p2.txt p3.txt", shell=True)

The reason you need to use shell=True in this case is that the copy command in Windows is not actually an executable but a built-in command of the shell (if memory serves right). xcopy on the other hand is a real executable (in %WINDIR%\System32, which is usually in the %PATH%), so it can be called outside of a cmd.exe shell.

In this particular instance, shutil.copy or shutil.copy2 might be viable alternatives.

Please note that using shell=True can lead to security hazards, or as the docs put it:

Warning: Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.

share|improve this answer
    
Any idea why it does work for xcopy? –  dwjohnston Jul 11 at 4:39
    
Updated my answer explaining why copy fails without shell=True. –  nmaier Jul 11 at 4:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.