0

I'm trying to make a program that will take a word from a .txt file and will press a keyboard key. I'm doing it so my Twitch chat can control my keyboard by a command. Below is the code without the key press (it doesn't work).

with open('C:\Users\laith\AppData\Roaming\HexChat\logs\Twitch\#liongenz9629.log') as file:
contents = file.read()
search_word = input("test2")
if search_word in contents:
    print ('word found')

else:
    print ('word not found')

I also can't figure out how to press a key. I tried including the following code:

Send {F down}{Fup}
Send {F down}{Fup}

to make this:

with open('C:\Users\laith\AppData\Roaming\HexChat\logs\Twitch\#liongenz9629.log') as file:
contents = file.read()
search_word = input("test2")
if search_word in contents:
    Send {F down}{Fup}
    Send {F down}{Fup}

else:
    print ('word not found')

But what I would like to know, is why it didn't work. I researched it extensively and could not find a fix, so alas here I am...

I am using Python 2.7.18 64-Bit


PC: Windows 10 Home Version 1903 Build 18362.959

Mansoor
  • 2,357
  • 1
  • 17
  • 27
mapch
  • 1
  • 1
  • Does this answer your question? [Python simulate keydown](https://stackoverflow.com/questions/11906925/python-simulate-keydown) – CoderCharmander Sep 11 '20 at 21:40

1 Answers1

0

Did you try the pynput package ? It should work on python 2.7.

To install execute

pip install pynput

Example from the documentation :

from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)

# Type a lower case A; this will work even if no key on the
# physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')

# Type two upper case As
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')

# Type 'Hello World' using the shortcut type method
keyboard.type('Hello World')
Mathieu Rollet
  • 2,016
  • 2
  • 18
  • 31