Windows can't find the file on subprocess.call()

Question:

I am getting the following error:

WindowsError: [Error 2] The system cannot find the file specified

My code is:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7, 64 bit. Python 3.x latest, stable.

Any ideas?

Thanks,

Asked By: Sri

||

Answers:

When the command is a shell built-in, add a shell=True to the call.

E.g. for dir you would type:

import subprocess
subprocess.call('dir', shell=True)

To quote from the documentation:

The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.

Answered By: Douglas Macdonald

On Windows, I believe the subprocess module doesn’t look in the PATH unless you pass shell=True because it use CreateProcess() behind the scenes. However, shell=True can be a security risk if you’re passing arguments that may come from outside your program. To make subprocess nonetheless able to find the correct executable, you can use shutil.which. Suppose the executable in your PATH is named frob:

subprocess.call([shutil.which('frob'), arg1, arg2])

(This works on Python 3.3 and above.)

Answered By: ptomato

On Windows you have to call through cmd.exe. As Apalala mentioned, Windows commands are implemented in cmd.exe not as separate executables.

e.g.

subprocess.call(['cmd', '/c', 'dir'])

/c tells cmd to run the follow command

This is safer than using shell=True, which allows shell injections.

Answered By: Sam Inverso

If you are using powershell, then in it will be subprocess.call(['powershell','-command','dir']). Powershell supports a large portion of POSIX commands

Answered By: Alexander Nozik

To quote from the documentation:

“Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use run() in many cases, but lots of existing code calls these functions.”

SO: instead of subprocess.call use subprocess.run for Python 3.5 and above

Answered By: Adrian Berca

After much head scratching, I discovered that running a file that is located in C:WindowsSystem32 while running a 32bit version of python on a 64bit machine is a potential issue, due to Windows trying to out-smart the process, and redirect calls to C:WindowsSystem32 to C:WindowsSysWOW64.

I found an example of how to fix this here:
http://code.activestate.com/recipes/578035-disable-file-system-redirector/

Answered By: RBN

I met the same issue while I was calling a PHP. The reason is PHP isn’t in PATH so the command PHP was not found. But PowerShell found it does exist in the current location and it suggests replacing the ‘PHP’ by the ‘.PHP’ if I trust this command. Then it runs well.

Answered By: michael xie
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.