Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 461
bzm3r Avatar asked Aug 23 '26 22:08

bzm3r


1 Answers

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'])
like image 198
Primusa Avatar answered Aug 25 '26 11:08

Primusa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!