python - 如何在 Jupyter 中获取单个字符输入?
问题描述
在 Jupyter 中,使用 python 3,我正在尝试运行一个单元格,该单元格应该在 for 循环中要求输入单个字符并将答案存储在列表中。我想避免使用 input() 以避免每次都按回车键。
在 Windows 中工作,我尝试过:
import msvcrt
charlist = []
for x in range(10):
print("Some prompt")
a = msvcrt.getch()
charlist.append(a)
但是在运行单元时,内核会卡在 getch() 行的第一个实例而不接受任何输入。有没有办法在 Jupyter 笔记本中做到这一点?
解决方案
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
有关更多详细信息,请查看它。 http://code.activestate.com/recipes/134892/
推荐阅读
- css - 使网格布局在 Internet Explorer 中工作
- python - answer的输出是重复的
- javascript - 使用角度我想通过只输入一个来输入两个具有相同名称但文件扩展名不同的文件
- c - 使用 C 使用函数查找最小值和最大值
- mysql - Spring boot Mysql Docker-compose在添加存储库层时无法连接
- sprite-kit - SpriteKit - 触摸移动,如何防止节点跳转到触摸位置
- c# - 如何自动注册服务
- azure - 访问密钥保管库机密时出现 UnknownHostException
- php - Illuminate\Database\QueryException SQLSTATE[42S22]:未找到列:1054 '字段列表'中的未知列'current_team_id'
- java - 在 java (Android) 中对 HTML 字符进行转义的可靠方法