我正在尝试在 Linux 上组合 getch 和 progressbar Python 模块,但我无法让它工作。我想用getch监听键盘输入来中断进度条,但是当我插入getch语句时,进度条拒绝自动更新,只有当我按下键盘上的按钮时才会更新。
我目前使用的代码如下。我正在使用 ProgressBar2 和 getch 模块,但我尝试使用 tqdm 和我自己的 getch 方法无济于事。
bar = progressbar.ProgressBar()
for i in range(101):
sleep(0.01)
bar.update(i)
ch = getch.getch()
在使用我自己的 getch 实现时,我已将问题范围缩小到以下代码中的“sys.stdin.read(1)”行。
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno(), termios.TCSADRAIN)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
在 Windows 上,使用 msvcrt 模块,我没有任何问题。