Python realizes automatically opening the terminal and executing commands (windows)

Recently, some students need to open multiple terminals at the same time and execute different codes in them. You can use xterminal in Linux, but not in Windows. You need to open multiple terminals manually, but this is time-consuming and laborious, so this article will automatically open the terminal and execute the command. , given the python code below.

1. Environment and code

1. Install pypiwin32

Install the pypiwin32 package in a virtual environment. Note that the version of pywin32 needs to be controlled below 305, otherwise there will be pitfalls (see the first part of Part 3). The 225 version is used here:

pip install pypiwin32
pip install pywin32==225

2. Code examples

Just look at the code, as shown below. In fact, the basic steps are:

    1. Define the codes corresponding to different keyboard characters
    1. Define the command string you need to enter
    1. open window
    1. Top window
    1. Enter command execution
import subprocess
import sys
from time import *
import win32api
import win32con
import win32gui

# 定义键盘的字符对应的16进制code
key_map = {
    
    
    "0": 0x30, "1": 0x31, "2": 0x32, "3": 0x33, "4": 0x34, "5": 0x35, "6": 0x36, "7": 0x37, "8": 0x38, "9": 0x39,
    'F1': 112, 'F2': 113, 'F3': 114, 'F4': 115, 'F5': 116, 'F6': 117, 'F7': 118, 'F8': 119,
    'F9': 120, 'F10': 121, 'F11': 122, 'F12': 123, 'F13': 124, 'F14': 125, 'F15': 126, 'F16': 127,
    "A": 65, "B": 66, "C": 67, "D": 68, "E": 69, "F": 70, "G": 71, "H": 72, "I": 73, "J": 74,
    "K": 75, "L": 76, "M": 77, "N": 78, "O": 79, "P": 80, "Q": 81, "R": 82, "S": 83, "T": 84,
    "U": 85, "V": 86, "W": 87, "X": 88, "Y": 89, "Z": 90,
    'BACKSPACE': 8, 'TAB': 9, 'TABLE': 9, 'CLEAR': 12,
    'ENTER': 13, 'SHIFT': 16, 'CTRL': 17,
    'CONTROL': 17, 'ALT': 18, 'ALTER': 18, 'PAUSE': 19, 'BREAK': 19, 'CAPSLK': 20, 'CAPSLOCK': 20, 'ESC': 27,
    ' ': 32, 'SPACEBAR': 32, 'PGUP': 33, 'PAGEUP': 33, 'PGDN': 34, 'PAGEDOWN': 34, 'END': 35, 'HOME': 36,
    'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, 'SELECT': 41, 'PRTSC': 42, 'PRINTSCREEN': 42, 'SYSRQ': 42,
    'SYSTEMREQUEST': 42, 'EXECUTE': 43, 'SNAPSHOT': 44, 'INSERT': 45, 'DELETE': 46, 'HELP': 47, 'WIN': 91,
    'WINDOWS': 91, 'NMLK': 144,
    '.':0xBE,
    'NUMLK': 144, 'NUMLOCK': 144, 'SCRLK': 145,
    '[': 219, ']': 221, '+': 107, '-': 109}


num = 5
# 定义一下你要输入的命令字符串
cmds = [f'python node.py {
      
      num} n{
      
      i + 1}' for i in range(num)]
cmds.append(f'python tester.py {
      
      num}')
for cmd in cmds:
	# 打开cmd
    subprocess.Popen('start C:\windows\system32\cmd.exe', shell=True)
    # sleep一下,因为windows11打开cmd比较慢,为了防止界面还没出现而误触,这样做一下比较保险
    sleep(0.2)

    #查找打开的窗口,findwindow(x,y)x是类别名,y是窗口标题
    n=win32gui.FindWindow('ConsoleWindowClass', None)

    # 置顶窗口
    p=win32gui.SetForegroundWindow(n)

    for chr in cmd:
        # print(chr.upper())
        # 按下按键
        win32api.keybd_event(key_map[chr.upper()], 0, 0, 0)
    win32api.keybd_event(13,0,0,0) #enter
    win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0)

2. Effect display

Insert image description here

As shown in the picture above, we have opened multiple command windows and executed the instructions we want to enter. Similarly, we can also open other software in a similar way.

3. Problems

1. ImportError: DLL load failed while importing win32api: The specified module cannot be found.

This usually means that the version of win32api is too high. Generally, it needs to be lower than version 302. You can use a lower version such as 225 or 226. The solution is as follows:

    1. pip install pypiwin32
    1. pip install pywin32==225

2. The window is open but no command is entered.

This is usually because the window handle is not captured or because it is too slow to open the window. There are two solutions:

  1. Use Microsoft's spy++ tool to check the class name of the window you are about to open. Take Windows Terminal as an example:

Insert image description hereInsert image description here
Using the search function in spy++, we can guide the class and title of the corresponding program to help us use the findwindow function to locate the handle. As can be seen here, the class name of cmd is ConsoleWindowClass,但是部分笔记本的win11上的cmd并不是这个类名,所有需要注意!!!!

  1. The window opens too slowly.
    At this time, modify the sleep time (unit is s) to allow some time for the window to open.
    Insert image description here

Guess you like

Origin blog.csdn.net/qq_36306288/article/details/128149517