How can I use the content of a file as a condition?

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?



Read more here: https://stackoverflow.com/questions/68475808/how-can-i-use-the-content-of-a-file-as-a-condition

Content Attribution

This content was originally published by Ernest Jorba at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: