python - 使用 prompt_toolkit 对按键做出反应
问题描述
我正在尝试使用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}')
我希望这个程序:
Ctrl+T
按下时打印“hello world” 。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()
那么如何创建一个改变我的变量的键绑定呢?
解决方案
您正在从局部函数引用全局变量,您只需要指出这是您想要的,否则您正在引用一个不存在的局部变量。
@bindings.add('d')
def _(event):
global i # fixes your problem
i *= 2
见上面的一行更改!
推荐阅读
- python - 如何检索字典中的列表?
- r - 如何使用 usethis 在谷歌云平台上增加我的 R 包的版本?
- javascript - 全屏菜单覆盖:如何使其淡入淡出?
- ios - 使用 AVAudioEngine 从外部 MIDI 垫播放声音
- c - 堆栈上的临时数据是否始终预设?
- javascript - 如何订购由仅包含一个对象的 firebase 集合
- php - 在共享主机上使用微风和 laratrust 部署 laravel 8
- r - 在 R 中缩放数据 - 我需要缩放数据框以避免前 9 列,但最终缩放的文件需要具有前 9 列
- r - 信息矩阵是奇异的,在 R (Lavaan)
- css - 从下到上显示聊天消息