How To Fix Python Subprocess Run Error FileNotFoundError: [winerror 2] The System Cannot Find The File Specified

When i execute a system program use python subprocess module’s run method in windows, i meet an error message like below.

>>> import subprocess

>>>["dir", "/p"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\", line 488, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\", line 800, in __init__
    restore_signals, start_new_session)
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\", line 1207, in _execute_child
FileNotFoundError: [WinError 2] The system cannot find the file specified

This error is because i run above command in a window shell, but do not specify the shell=True argument in subprocess module’s run method. After i add shell=True argument in subprocess module’s run method, it runs successfully like below.

>>> import subprocess
>>> ret =["dir", "/p"], shell=True)
 Volume in drive C has no label.
 Volume Serial Number is C01B-6F8A

 Directory of C:\Users\zhaosong

07/07/2020  18:58    <DIR>          .
07/07/2020  18:58    <DIR>          ..
02/08/2020  19:13    <DIR>          Videos
               2 File(s)             50 bytes
              23 Dir(s)  173,195,341,824 bytes free
>>> ret
CompletedProcess(args=['dir', '/p'], returncode=0)

The subprocess module’s run method return an instance of subprocess.CompletedProcess class, it records the completed process status data (ie: executed command, return code etc.)


  1. subprocess — Subprocess management
0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x