I am in the same situation as the person who asked this question and at the same time he managed to answer it using "win32(something)" instead of "subprocess": how to open a cmd shell in windows and issue commands to that shell using python
I am partially satisfied with this answer, but I have encountered a new problem: How do I "capture" the outputs (strings) generated by each command line (or at least the last command line used)?
To give you a more contextual idea, I use a program that requires command lines in cmd.exe (imagemagick), I use it to compare images and, using a complex statistical criterion, I obtain a floating number between 0 and 1.
Precisely that number is the one I want to capture.
This is my current code:
import time import os from win32com import client from win32gui import GetWindowText, GetForegroundWindow, SetForegroundWindow, EnumWindows from win32process import GetWindowThreadProcessId
class ActivateVenv:
def set_cmd_to_foreground(self, hwnd, extra): """sets first command prompt to forgeround""" if "cmd.exe" in GetWindowText(hwnd): SetForegroundWindow(hwnd) return def get_pid(self): """gets process id of command prompt on foreground""" window = GetForegroundWindow() return GetWindowThreadProcessId(window)[1] def activate_venv(self, shell, venv_location): """activates venv of the active command prompt""" shell.AppActivate(self.get_pid()) #shell.SendKeys("cd \ {ENTER}") #shell.SendKeys(r"cd %s {ENTER}" % venv_location) #shell.SendKeys("activate {ENTER}") def run_py_script(self,shell): """runs the py script""" shell.SendKeys("cd ../..{ENTER}") shell.SendKeys("python run.py {ENTER}") def run_script(self,shell,command_line): """runs a general script""" shell.SendKeys(command_line) def open_cmd(self, shell): """ opens cmd """ shell.run("cmd.exe") time.sleep(1) def comparar(p,q): try: return 'magick compare -metric ncc C:\GTSgiffer\INput\{}.png C:\GTSgiffer\INput\{}.png null: 2>&1'.format(p,q) except: print(f"Error en comparar({p},{q})") pass if __name__ == "__main__": '''shell = client.Dispatch("WScript.Shell") run_venv = ActivateVenv() run_venv.open_cmd(shell) EnumWindows(run_venv.set_cmd_to_foreground, None) run_venv.activate_venv(shell, "flask3.5/venv/scripts") run_venv.run_py_script(shell)''' shell = client.Dispatch("WScript.Shell") run_venv = ActivateVenv() run_venv.open_cmd(shell) EnumWindows(run_venv.set_cmd_to_foreground, None) run_venv.activate_venv(shell, "flask3.5/venv/scripts") run_venv.run_script(shell,r"cd C:\GTSgiffer\bin {ENTER}") run_venv.run_script(shell,comparar(1,2)+" {ENTER}") run_venv.run_script(shell,comparar(1,3)+" {ENTER}")
subprocess?