使用python模拟应用程序中的按键



我正在尝试编写一个python脚本,该脚本将从文本文档中键入行,就像它们来自键盘一样。我已经在一些应用程序中有了一个代码片段(见下文(,这会正确地键入我打开的文件中的每一行,例如,我将输出测试到notepad++中,它会将其全部键入。

import keyboard
import time
time.sleep(3) """ this gives me enough time to alt-tab into the game (Witcher 3) 
that I am trying to have the keypresses inserted into, I also tried some code with 
win32gui that brough the Witcher 3 app to the front, but this is simpler. """
with open('w3recipes.txt', 'r', encoding='utf-8') as recipes:
for line in recipes:
keyboard.write(line)
time.sleep(0.05)

问题是,这些按键没有被Witcher 3注册,我正试图将所有这些按键写入该游戏。我尝试将游戏从全屏更改为窗口,但没有成功,我尝试将脚本编译为.exe并以管理员身份运行,没有骰子。我还尝试了pynput库,而不是这里使用的键盘库,结果相同。

如果有任何帮助,我将不胜感激,我正试图为这款游戏编写几百个控制台命令,但游戏控制台中没有换行符;在点击回车键之前,它一次只支持一个命令。我唯一的选择是坐在这里复制粘贴所有令人厌倦的行。

提前谢谢。

使用另一个库pydirectinput。这是pyautogui的更新版本,我发现它适用于大多数(如果不是所有的话(游戏。

引用文档:

此库旨在复制PyAutoGUI鼠标和键盘输入的功能,但使用DirectInput扫描代码和更现代的SendInput((win32函数。PyAutoGUI使用虚拟密钥代码(VK(以及不推荐使用的mouse_event((和keybd_event(win32函数。您可能会发现PyAutoGUI在某些应用程序中不起作用,尤其是在视频游戏和其他依赖DirectX的软件中。如果你发现自己处于这种情况,试试这个图书馆吧!

写入函数:

>>> import pyautogui
>>> import pydirectinput
>>> pydirectinput.moveTo(100, 150) # Move the mouse to the x, y coordinates 100, 150.
>>> pydirectinput.click() # Click the mouse at its current location.
>>> pydirectinput.click(200, 220) # Click the mouse at the x, y coordinates 200, 220.
>>> pydirectinput.move(None, 10)  # Move mouse 10 pixels down, that is, move the mouse relative to its current position.
>>> pydirectinput.doubleClick() # Double click the mouse at the
>>> pydirectinput.press('esc') # Simulate pressing the Escape key.
>>> pydirectinput.keyDown('shift')
>>> pydirectinput.keyUp('shift')
# And this is the one you want,
>>> pydirectinput.write('string') # Write string
>>> pydirectinput.typewrite("string")

最新更新