[Python] Writing sequence of commands to CMD, waiting for outputs

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a sequence of commands to a cmd window. One of the problems I'm facing is that I'm utilizing Engineering Sketch Pad (ESP), which opens a cmd terminal (named "ESP126") that I need these commands to write to, so I'm not able to open my own cmd. Likewise, this process needs to happen in the background, and multiple commands need to wait for prior commands to be finished before running, so using keystrokes or typewrite commands is not favorable.

    Any thoughts?

    Example code I'm working with (with typewrite commands, because I couldn't think of another way to do this).

    def run_cmd(cmd_process, command):
    """Run a command in the opened CMD window."""
    cmd_process.stdin.write(f'{command}\n')
    cmd_process.stdin.flush()

    # Start ESP using the shortcut (outputs cmd window)
    shortcut = r"mypath\ESP126.lnk" # shortcut to ESP
    os.startfile(shortcut)
    time.sleep(2)

    # Find the CMD window
    windows = gw.getWindowsWithTitle("ESP126")
    if windows:
    cmd_window = windows[0]
    cmd_window.activate()
    time.sleep(1)

    # Send change directory command to cmd window
    pyautogui.typewrite(r'cd {new directory}')
    pyautogui.press('enter')
    time.sleep(1)

    # Send ESP serve command to cmd
    pyautogui.typewrite(r'ServeESP fileone.csm')
    pyautogui.press('enter')

    # Send another ESP serve command to cmd
    pyautogui.typewrite(r'ServeESP filetwo.csm')
    pyautogui.press('enter')
    else:
    print("CMD window not found.")

    Continue reading...

Compartilhe esta Página