I installed AutoKey on my computer so I can execute python files with the keyboard, and what I want to do is execute a script as a loop but also being able to stop it.
The script presses the “d” key on my keyboard, waits around 2.4 seconds, and then presses “s”. What I thought would be a good idea is this:
import time import random from pynput.keyboard import Key, Controller keyboard = Controller() file = open("file.txt", "r+") file.write("1") while file.read == 1: keyboard.press("d") time.sleep((random.randrange(24075, 24221))/10000) keyboard.release("d") keyboard.press("s") time.sleep((random.randrange(24075, 24221))/10000) keyboard.release("s") file.close()
And the other file that executes with a different hotkey to stop the previous script:
def main() : file = open("file.txt", "w") file.write("0") file.close() main()
The problem that I find is that this doesn’t work. When I execute the first script it just doesn’t go to the while
part like it doesn’t detect that’s supposed to be enabled.
Is there an easier way to do this or am I just messing up somewhere and I can’t find it?
Advertisement
Answer
the problem is that you are not setting the cursor position in the file to the beginning before you read the file. So when you run it it reads the file while the cursor in the file is located at the end of the file. So the returned String is always empty and so it stops the while loop.
With file.seek(0)
you can set the cursor position to the beginning of the file. I also would recommend using with
statements. This automatically closes the file when you are going out of indentation. My approach is like this:
import time import random from pynput.keyboard import Key, Controller keyboard = Controller() with open("file.txt", "r+") as file: file.write("1") file.seek(0) while file.read() == "1": keyboard.press("d") time.sleep((random.randrange(24075, 24221))/10000) keyboard.release("d") keyboard.press("s") time.sleep((random.randrange(24075, 24221))/10000) keyboard.release("s") file.seek(0)
And this for stopping the above script:
def main() : with open("file.txt", "w") as file: file.write("0") main()