Python не читает переменную из отдельного файла - PullRequest
0 голосов
/ 15 января 2020

Я попытался изменить скрипт Autoclicker на веб-сайте pynput, чтобы он сохранял нажатую кнопку мыши в файле mousebutton.txt. Однако оператор if, похоже, не определяет 2 переменные, основанные на одной строке в mousebutton.txt. (которое должно быть 1 или 2)

# attempts to read from mousebutton.txt -- if it is not found, it creates it. 
try:
    with open('mouseButton.txt', 'r') as mbfile:
        # read a list of lines into data if file found 
        mbdata = mbfile.readlines()
except FileNotFoundError as e:
    if e.errno == errno.ENOENT:
        # FileNotFoundError code here
        with open('mouseButton.txt', 'a') as mbfile:
            mbfile.write("0")
            mbfile.close()
    else:
        raise
finally:
    with open('mouseButton.txt', 'r') as mbfile:
        # read a list of lines into data
        mbdata = mbfile.readlines()

# saved mouse button
if mbdata == "0":
    button = Button.left
    currentButton = "left"
    print("Current button: " + currentButton)
elif mbdata == "1":
    button = button.right
    currentButton = "right"
    print("Current button: " + currentButton)
else:
    button = Button.left
    currentButton = "left"
    print("Current button: " + currentButton)

Позже в коде, где он закрывается mousebutton.txt

# closing mousebutton.txt
with open('mouseButton.txt', 'w') as file:
            # file.writelines( data )
            data_amount = 0
            for x in range(read_lines):
                file.write(mbdata[data_amount])
                data_amount = data_amount + 1
                file.write("\n")
        file.close()
click_thread = ClickMouse(delay, button)
click_thread.start()

Я получаю здесь ошибку, говоря: :

line 160, in <module>
    click_thread = ClickMouse(delay, button)
NameError: name 'button' is not defined
...