0

我正在尝试在 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 模块,我没有任何问题。

4

1 回答 1

0

我在 Linux 上遇到了同样的问题,所以我选择了不同的解决方案:捕获 SIGINT 信号 (CTRL+C) 以优雅退出,或在两次按下后立即退出(常规 SIGINT 方式)。

import signal
import time

signal.signal(signal.SIGINT, signal_handler)
sigint_again = False
asked_termination = False

def signal_handler(self, signal, frame):
    """Handles SIGINT signal, blocks it to terminate gracefully"""
    print('You pressed Ctrl+C!:', signal, frame)
    if is_sigint_called_twice():
        print("\nForced terminating script!")
        sys.exit(0)
    asked_termination = True

def is_sigint_called_twice(self):
    """Check if pressing ctrl+c a second time to terminate immediately"""
    if not sigint_again:
        sigint_again = True
        return False
    else:
        return True

while not asked_termination:
    print("do_stuff()")
    time.sleep(1)
于 2017-09-20T18:19:03.870 回答