python - 如何使用 curses stdscr.getch() 在 MacOS 上的 Jupyter Notebook 中捕获按键?
问题描述
我在 MacOS 上使用带有 Python 3.7 的 Jupyter Notebook
我收集了很多数据,现在我想一次绘制一个图表,并使用 for 循环在图表中循环。但是,我想暂停查看每个图表 - 并按任意键继续查看下一个图表。
我尝试了 input('Press ENTER to continue...') 但它会在每个图形之后创建一个新行,并且每次我按 Enter 时都会使整个 Jupyter 单元格输出向上滚动,因为它会为每个输入创建一个新行。
所以我正在尝试使用 curses 库 stdscr.getch() 来捕获键盘输入 - 但是它没有检测到任何键盘按键。
import curses
%matplotlib notebook
fig,ax = plt.subplots(figsize=(10, 8))
ch = 1
for col in df.columns:
if int(col) % 2 == 0: # even columns are time
xs = df[col]
else: # odd columns are voltage
if ch == 2:
ys = df[col]
ax.plot(xs, ys, 'b')
ax.set_xlabel('X') ; ax.set_ylabel('Y')
ax.set_xlim(-30,260) ; ax.set_ylim(-10000,10000)
fig.canvas.draw()
#input('Press ENTER to continue...')
stdscr = curses.initscr()
stdscr.keypad(True)
while True:
key = stdscr.getch()
if key != -1:
print(key)
if key == 27: # This is the escape key code
curses.endwin()
break
ax.cla()
ch = 1
else:
ch = 2
但是,在 while True 循环中,key 始终为 -1。无论我按什么键,键总是-1,这意味着它根本没有检测到任何键盘按键。我错过了什么?如何使用 stdscr.getch() 从 MacOS 上的 Jupyter Notebook 中检测按键?
谢谢!
解决方案
任何 Jupyter 笔记本中的 Python 代码在服务器内运行,n/curses 或任何其他类似的库将尝试获取服务器的键盘,否则 Jupyter 将禁用它。因此,ncurses 将无法捕获按键。
你最好的选择是@Tiago 所说的:Jupyter Widgets and event handlers for that。但是,这仅适用于 Jupyter,不适用于在 bash 上运行的 Python。
https://minrk-ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html
从上面的网站:
t = widgets.Text(
value='Hello World',
placeholder='Type something',
description='String:',
disabled=False
)
def on_enter():
print('enter key pressed')
t.on_submit(on_enter)
推荐阅读
- javascript - 使用 javascript 和 localstorage 刷新后如何保留输入结果?
- html - 带有 ssl 和 www 重定向的 Angular 通用 Web 配置文件
- java - Spring批处理IllegalStateException进行更新
- java - 调整基本足球模拟算法
- python - 如何在 PYQT5 菜单栏中同时显示图标和文本
- javascript - Vue.set 更新 Vuex 存储中复制的对象
- python - 在 Django 中基于类的视图中转换函数视图
- javascript - 将 1 个 JS If 语句应用于多个 HTML ID
- r - 使用 mutate 和 recode 函数的语法有什么问题?
- python - 递归符号计算 - 提高性能