dwjohnston
dwjohnston

Reputation: 11771

The system cannot find the file specified when calling copy from python

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?

Upvotes: 2

Views: 2426

Answers (1)

nmaier
nmaier

Reputation: 33162

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.

Upvotes: 5

Related Questions