bzm3r
bzm3r

Reputation: 4596

Cannot find the file specified when using subprocess.call('dir') in Python

I am on Windows 10, and I run the following Python file:

import subprocess

subprocess.call("dir")

But I get the following error:

  File "A:/python-tests/subprocess_test.py", line 10, in <module>
    subprocess.call(["dir"])

  File "A:\anaconda\lib\subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:

  File "A:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 210, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "A:\anaconda\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)

  File "A:\anaconda\lib\subprocess.py", line 997, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

Note that I am only using dir as an example here. I actually want to run a more complicated command, but I am getting the same error in that case too.

Note that I am not using shell=True, so the answer to this question is not applicable: Cannot find the file specified when using subprocess.call('dir', shell=True) in Python

This is line 997 of subprocess.py:

hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         os.fspath(cwd) if cwd is not None else None,
                                         startupinfo)

When I run the debugger to check out the arguments being passed to CreateProcess, I notice that executable is None. Is that normal?

Upvotes: 3

Views: 23244

Answers (2)

Taku
Taku

Reputation: 33704

You must set shell=True when calling dir, since dir isn't an executable (there's no such thing as dir.exe). dir is an internal command that was loaded with cmd.exe.

As you can see from the documentation:

On Windows with shell=True, the COMSPEC environment variable specifies the default shell. 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.

Upvotes: 6

Primusa
Primusa

Reputation: 13498

dir is a command implemented in cmd.exe so there is no dir.exe windows executable. You must call the command through cmd.

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

Upvotes: 6

Related Questions