Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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,
                                         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?

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'])

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.