I\'ve tried
import os
os.system(\'cmd.exe\')
great it opens up a cmd shell
but how do I write commands from my python script so tha
to anyone having the same problems as me
I needed to get a handle on the command prompt window and and wanted to activate my virtualenv and run my .py
file programatically.
I used pywin32com and after hours of researching stackoverflow and the web
I managed to get a working solution
I don't know much about the subprocess module but and I don't know if it let's you send different commands to the opened command prompt
but here is my working solution
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 open_cmd(self, shell):
""" opens cmd """
shell.run("cmd.exe")
time.sleep(1)
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)
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
The command variable should be for example: cmd /k
. You can also add a stdin=subprocess.PIPE
to the Popen argument list and write commands to cmd:
subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stdin=subprocess.PIPE)
the final code:
import subprocess
process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir") #passing command
stdOutput,stdError = process.communicate()
print stdOutput
process.stdin.close()
Or alternatively:
from subprocess import *
Popen("cmd /k dir")