'How to replace keyboard output using python
I am not exactly sure how to word this question so I'll try to explain my problem here.
I am trying to code a program that reads text (for example an essay) from a txt file and then types each letter from that txt file as you type a letter on the keyboard (think those hacker games where you mash the keyboard and it looks like you're typing something that you are not).
Currently I am handling this by simply deleting the character right after but I noticed that I needed to add a delay for this to work with any stability whatsoever. A delay of 0.05 works okay, but any lower is unstable and 0.05 is already far too much for my liking. I also tried using keyboard.press_and_release() but this needed just as large of a delay without breaking.
I am using the keyboard module because it works on both Windows and Mac which is a must have. I am also not exactly sure that I understand why this is happening especially with the press and release function so hopefully someone might know an answer or maybe a different module to use. I have also tried pyautogui and that was even worse.
import pyautogui
import time
import keyboard
# only keyboard needs to be pip installed i think
if __name__ == '__main__':
keyboard.wait("ctrl")
time.sleep(2)
inFile = open('Essay', 'r')
while True:
line = inFile.readline();
# if line is empty meaning file is reached
if not line:
break
while len(line) > 0:
keyboard.read_key()
time.sleep(0.05)
keyboard.press("backspace")
time.sleep(0.05)
keyboard.press(line[0])
line = line[1:len(line)]
time.sleep(0.05)
keyboard.press("enter")
Solution 1:[1]
I am not sure but it may help you. Install the PyPI package:
pip install keyboard
or clone the repository (no installation required, source files are sufficient):
git clone https://github.com/boppreh/keyboard
or download and extract the zip into your project folder.
Then check the API docs below to see what features are available.
Example:
import keyboard
keyboard.press_and_release('shift+s, space')
keyboard.write('The quick brown fox jumps over the lazy dog.')
keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))
# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))
# Blocks until you press esc.
keyboard.wait('esc')
# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)
# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', '[email protected]')
# Block forever, like `while True`.
keyboard.wait()
Courtesy: https://softans.com/how-to-replace-keyboard-output-using-python/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GHULAM NABI |
