When I execute a system program using the python subprocess module’s run method in windows, I meet an error message like below.
1. The FileNotFoundError: [WinError 2] The System Cannot Find The File Specified.
Below is the detailed error message and the steps to reproduce it.
>>> 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 the above command in a window shell, but do not specify the shell=True argument in the subprocess module’s run method.
After I add the shell=True argument in the 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 returns an instance of the subprocess.CompletedProcess class, this object records the completed process status data (ie: executed command, return code, etc.)
2. Question & Answer.
2.1 The FileNotFoundError: [WinError 2] Occurred When Use Python Subprocess Module’s Popen() Method.
I use the python subprocess module’s Popen function to execute a windows executable program like below, and it throws the FileNotFoundError: [WinError 2].
import subprocess as sp import os # This function will call the python subprocess module's Popen method to invoke a system executable program. def subprocess_popen_exmple(): # Create the windows executable file command line arguments array. cmd_param_arrray = [] # Add the command line arguments cmd_param_arrray.append('start ') cmd_param_arrray.append('/wait ') # Get the windows system directory win_dir_path = os.environ['WINDIR'] + "\\System32\\" # Get the windows executable file ( notepad.exe ) path. cmd_executeable_file_path = os.path.join(win_dir_path, 'notepad.exe') # Add the above windows executable file path to the command line arguments list. cmd_param_arrray.append(cmd_executeable_file_path) # Print out the command line arguments list elements. print(cmd_param_arrray) # Invoke the windows program with the python subprocess module's Popen() method. child = sp.Popen(cmd_param_arrray) if __name__ == '__main__': subprocess_popen_exmple()
Below is the detailed error message.
['start ', '/wait ', 'C:\\Windows\\System32\\notepad.exe'] Traceback (most recent call last): File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\thread\SubProcessExample.py", line 38, in <module> subprocess_popen_exmple() File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\thread\SubProcessExample.py", line 34, in subprocess_popen_exmple child = sp.Popen(cmd_param_arrray) File "C:\Users\zhaosong\anaconda3\lib\subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\zhaosong\anaconda3\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] \u7cfb\u7edf\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u6587\u4ef6\u3002
To fix this error is very easy, you just need to add the windows executable file path as the first argument in the command line arguments list, then you can run the executable file sucessfully.
import subprocess as sp import os # This function will call the python subprocess module's Popen method to invoke a system executable program. def subprocess_popen_exmple(): # Create the windows executable file command line arguments array. cmd_param_arrray = [] # Get the windows system directory win_dir_path = os.environ['WINDIR'] + "\\System32\\" # Get the windows executable file ( notepad.exe ) path. cmd_executeable_file_path = os.path.join(win_dir_path, 'notepad.exe') # Add the above windows executable file path to the command line arguments list. cmd_param_arrray.append(cmd_executeable_file_path) # Add the command line arguments cmd_param_arrray.append('start ') cmd_param_arrray.append('/wait ') # Print out the command line arguments list elements. print(cmd_param_arrray) # Invoke the windows program with the python subprocess module's Popen() method. child = sp.Popen(cmd_param_arrray) if __name__ == '__main__': subprocess_popen_exmple()
Thank you so much. Had been struggling to move my python script from windows to linux just 2 days before presentation
I am very happy that my post helped you, you are welcome to my website:)
Thank you. This was very helpful. The sharing of your expertise is appreciated!