簡體   English   中英

使用 Python 在批處理腳本中按下一個鍵

[英]Press a key in a batch script with Python

我在 python 中有一個腳本,它執行一個批處理程序,需要在“d”鍵和“q”鍵之后按兩到三次。

我試過這個但沒有解決方案:

import os
import keyboard
import time
from pynput.keyboard import Key, Controller

os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)

keyboard = Controller()
keyd = "d"
keyq = "q"

keyboard.press(keyd)
keyboard.release(keyd)
time.sleep(3)
keyboard.press(keyq)
keyboard.release(keyq)

只打開控制台,但腳本不按下鍵,但如果你用鍵盤按下程序工作正常。

您可以嘗試使用subprocess模塊。

例子:

subprocess-test.py

import subprocess

p = subprocess.Popen(["python", "input-app.py"], stdin=subprocess.PIPE)

p.stdin.write("Hello\n".encode(encoding='UTF-8'))
p.stdin.write("World\n".encode(encoding='UTF-8'))

input-app.py

input1 = input("Input 1: ")
input2 = input("Input 2: ")

print(input1, input2)

在此處查看更多信息:

抱歉,我無法提供更多幫助,因為我只有短暫的午休時間。 我希望這已經有所幫助或為您指明正確的方向!

您可以使用: pyautogui簡單地按下代碼:

import pyautogui
pyautogui.press('d')

您的情況可以按以下方式處理:

import os
import pyautogui
import time

os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)

keyd = "d"
keyq = "q"

pyautogui.press(keyd)
time.sleep(3)
pyautogui.press(keyq)

如果按鍵不起作用,您也可以嘗試輸入確切的字符串:

import os
import pyautogui
import time

os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)

keyd = "d"
keyq = "q"

pyautogui.write(keyd)
time.sleep(3)
pyautogui.write(keyq)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM