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

>>> subprocess.run(["dir", "/p"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\subprocess.py", line 488, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)
  File "C:\Users\zhaosong\anaconda3\envs\env_python_37\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)
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 = subprocess.run(["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.)

Reference

  1. subprocess — Subprocess management
READ :   How To Pass Multiple Parameters Via Url In Django

Leave a Reply

Your email address will not be published. Required fields are marked *

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