【问题标题】:How to output while waiting for a character input in Python 3?如何在 Python 3 中等待字符输入时输出?
【发布时间】:2020-06-22 21:41:23
【问题描述】:

我想制作一个需要空格键来停止它的计时器。我还想打印出自循环开始以来已经过去了多少时间。我试过这个:

import msvcrt
import time

print("Press space")
start_time = time.time()
while True:
    # print how much time has passed
    print(start_time - time.time(), end='\r')

    # break the loop if space btn was pressed
    if msvcrt.getch() == b" ":
        break

但问题是只有当我按下一个键时才会打印经过的时间,我希望它继续打印出来。我从https://stackoverflow.com/a/22391379/12132452 尝试了这个解决方案,但是因为它是 python 2,所以我一直收到这个错误

Traceback (most recent call last):
  File "f:/Projects/Python/test.py", line 9, in <module>
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failed

我需要做什么?

【问题讨论】:

    标签: python


    【解决方案1】:

    这可能会有所帮助:

    import sys
    import keyboard
    import time
    
    print("Press space")
    start_time = time.time()
    while True:
        try:
    
            print(start_time - time.time(), end='\r')
            if keyboard.is_pressed('SPACE'):
                print("\nyou pressed SPACE, exiting...")
                sys.exit()
        except:
            break
    

    【讨论】:

    • ModuleNotFoundError: No module named 'keyboard'
    • 用 python -m pip install keyboard 安装
    【解决方案2】:

    我知道这个问题已经得到解答,但这是 pygame 中的另一种方法:

    import pygame
    import time
    
    pygame.init()
    
    wn = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Timer')
    
    start_time = time.time()
    
    def main():
        running = True
        fps = 60
        clock = pygame.time.Clock()
        
        while running:
            clock.tick(fps)
    
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
            
            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE]:
                print(time.time() - start_time)
                running = False
            
            pygame.display.update()
    
    main()
    

    另外,要安装 pygame,请打开终端并输入:

    python -m pip install pygame==1.9.6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多