how to open a cmd shell in windows and issue commands to that shell using python

前端 未结 2 1460
执笔经年
执笔经年 2020-12-11 13:56

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

2条回答
  •  没有蜡笔的小新
    2020-12-11 13:59

    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)
    

提交回复
热议问题