简体   繁体   English

使用 Python 在批处理脚本中按下一个键

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

I have a script in python that execute a batch program that need press two or three times the "d" key and after the "q" key.我在 python 中有一个脚本,它执行一个批处理程序,需要在“d”键和“q”键之后按两到三次。

I tried this but without solution:我试过这个但没有解决方案:

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)

Only open the console but the script don't press the keys, but if you press with the keyboard the program works fine.只打开控制台,但脚本不按下键,但如果你用键盘按下程序工作正常。

You could try to use the subprocess module.您可以尝试使用subprocess模块。

Example:例子:

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)

See more information here:在此处查看更多信息:

Sorry, I won't be able to help more as I only have a short lunch break.抱歉,我无法提供更多帮助,因为我只有短暂的午休时间。 I hope this already does help though or points you in the right direction!我希望这已经有所帮助或为您指明正确的方向!

You can use: pyautogui for pressing code as simply as:您可以使用: pyautogui简单地按下代码:

import pyautogui
pyautogui.press('d')

Your case can be handled as follows:您的情况可以按以下方式处理:

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)

If pressing keys don't work, you may try to enter exact strings as well:如果按键不起作用,您也可以尝试输入确切的字符串:

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