【问题标题】:Input without stopping program输入不停止程序
【发布时间】:2017-01-02 15:05:29
【问题描述】:

我正在尝试制作一个倒数计时器来打印剩余时间,当您输入内容时,它会打印您输入的内容。我的问题是我不想等待输入,只是继续运行计时器。我的错误代码:

timer = 100
while True:
    print(timer)
    timer -= 1

    if input('> '):
        print('the output of input')

你可以说我想让计时器在后台打印时间。

【问题讨论】:

  • 寻找 getch() 或类似的函数 - 它不在标准库中。
  • 如果你使用的是类似unix的操作系统,你可以select([sys.stdin]),或者使用curses.getch,如果在Windows上,那就更复杂了。
  • so if select([sys.stdin]) != '' then do x
  • 您也可以使用threading.Timer 对象并保持阻塞input 调用。

标签: python multithreading python-3.x python-multithreading python-asyncio


【解决方案1】:

这是一个在没有输入时会超时的函数:

import select
import sys

def timeout_input(timeout, prompt="", timeout_value=None):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    ready, _, _ = select.select([sys.stdin], [], [], timeout)
    if ready:
        return sys.stdin.readline().rstrip('\n')
    else:
        sys.stdout.write('\n')
        sys.stdout.flush()
        return timeout_value

您可以通过将select.select 上的超时值更改为1 并循环timeout 次来轻松修改它以显示剩余时间。

【讨论】:

    【解决方案2】:

    标准输入和标准输出(通过input()print() 访问)不是编写交互式异步用户界面(UI)的好选择。 Python 通过它的标准库支持一些 UI。例如,curses 是许多 POSIX 系统上可用的基于文本的用户界面。这是一个示例代码,用于在接受用户的数字时显示倒数计时器:

    import time
    import curses
    
    
    def get_number(seconds):
        def _get_number(stdscr):
            stdscr.clear()
            timeout = time.time() + seconds
            s = ""
            while time.time() <= timeout:
                time_left = int(timeout - time.time())
                stdscr.addstr(0, 0, 'Countdown: {} {}'.format(time_left,
                                                              "*" * time_left + " " * seconds))
                stdscr.addstr(2, 0, ' ' * 50)
                stdscr.addstr(2, 0, 'Your Input: {}'.format(s))
                stdscr.refresh()
                stdscr.timeout(100)
                code = stdscr.getch()
                stdscr.addstr(10, 0, 'Code: {}'.format(code))  # for debug only
                stdscr.refresh()
                if ord("0") <= code <= ord("9"):
                    s += chr(code)
                    continue
    
                if code == 10 and s:  # newline
                    return int(s)
    
                if code == 127:  # backspace
                    s = s[:-1]
    
        return curses.wrapper(_get_number)
    
    print(get_number(10))
    

    【讨论】:

    • 这个问题是我需要接受 2 位长度的字符串。
    • 所以不要写if code == 10 and s if len(s) == 2
    • getch 没有得到 1 个字符?
    • 是的,但请参见上面带有s += ... 的循环。只需尝试代码。
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2014-06-04
    相关资源
    最近更新 更多