首页 > 解决方案 > 如何使用 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 中检测按键?

谢谢!

标签: pythonjupyter-notebookkeyboard-eventscurses

解决方案


任何 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)

推荐阅读