如何使用文件的内容作为条件?

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

我在我的电脑上安装了 AutoKey,所以我可以用键盘执行 python 个文件,我想做的是循环执行一个脚本,但也能够停止它。

脚本按下我键盘上的“d”键,等待大约 2.4 秒,然后按下“s”。我认为这是个好主意:

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()

以及另一个使用不同的热键执行以停止上一个脚本的文件:

def main() :

    file = open("file.txt", "w")
    file.write("0")
    file.close()

main()

我发现的问题是这不起作用。当我执行第一个脚本时,它不会转到 while 部分,就像它没有检测到应该启用的部分一样。

有没有更简单的方法来做到这一点,或者我只是在某个地方搞砸了,我找不到它?

问题是您在读取文件之前没有将文件中的光标位置设置到开头。因此,当您 运行 它读取文件时,文件中的光标位于文件末尾。所以返回的字符串总是空的,所以它停止了 while 循环。 使用 file.seek(0) 可以将光标位置设置为文件的开头。我还建议使用 with 语句。当您离开缩进时,这会自动关闭文件。我的做法是这样的:

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)

这是为了停止上面的脚本:

def main() :
    with open("file.txt", "w") as file:
        file.write("0")

main()