Я пытаюсь использовать prompt_toolkit
, чтобы получить ввод от пользователя, не дожидаясь, пока он нажмет Enter. Мне удалось создать события и связать их с ключами, но я не могу понять, как на самом деле манипулировать моей программой из событий.
from prompt_toolkit import prompt
from prompt_toolkit.application import run_in_terminal
from prompt_toolkit.key_binding import KeyBindings
i = 2
bindings = KeyBindings()
@bindings.add('c-t')
def _(event):
" Say 'hello' when `c-t` is pressed. "
def print_hello():
print('hello world')
run_in_terminal(print_hello)
@bindings.add('c-x')
def _(event):
" Exit when `c-x` is pressed. "
event.app.exit()
@bindings.add('d')
def _(event):
i *= 2
text = prompt('> ', key_bindings=bindings)
print(f'You said: {text}')
print(f'i is now {i}')
Я ожидаю, что эта программа:
- Вывести «hello world» при нажатии
Ctrl+T
. - Выход при нажатии
Ctrl+X
. - Удвоить значение
i
при нажатии d
.
Это делает 1 и 2, но 3 дает Exception local variable 'i' referenced before assignment
. Но даже в документации Python мы видим пример (https://docs.python.org/3/reference/executionmodel.html):
i = 10
def f():
print(i)
i = 42
f()
Итак, как мне сделать связывание ключей, которое изменяет мою переменную?