Home > Mobile >  Unable to run windows command using subprocess.Popen
Unable to run windows command using subprocess.Popen

Time:12-01

I'm trying to run a simple windows command dir E:\Projects\ML /s /b using subprocess.Popen function without using Shell=True, my sample program is below

import subprocess
import os
import time

input='E:\Projects\ML'
command = "dir " input ' /s /b '
os.system(command)
status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE)
while status.wait()!=0:
    time.sleep(1)
print(status.communicate())

with os.system() the command is giving appropriate results but with Popen() I'm facing below problem

Traceback (most recent call last):
  File "e:\Projects\ArchiveViewer\PythonR&D\EncriptionWithPopen\runLocalCMD.py", line 9, in <module>
    status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE)
  File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

I know that if I set shell=True the command will run, but is there any reason why it is not working with shell=Fales

CodePudding user response:

dir is an internal command inside cmd.exe, there is no dir.exe that can be started as a process.

system("xyz") is internally executed as something like cmd.exe /C xyz on Windows.

  • Related