>백엔드 개발 >파이썬 튜토리얼 >Python 콘솔 애플리케이션에서 비차단 사용자 입력을 어떻게 구현할 수 있습니까?

Python 콘솔 애플리케이션에서 비차단 사용자 입력을 어떻게 구현할 수 있습니까?

Susan Sarandon
Susan Sarandon원래의
2024-12-01 01:46:09936검색

How Can I Implement Non-Blocking User Input in Python Console Applications?

콘솔 애플리케이션의 비차단 사용자 입력

다른 프로세스와 동시에 사용자 입력이 필요한 콘솔 애플리케이션을 구축할 때는 비차단이 필수적입니다. -입력을 기다리는 동안 프로그램이 멈추는 것을 방지하기 위해 입력을 차단합니다.

사용 msvcrt 모듈(Windows)

Windows 전용 콘솔 애플리케이션의 경우 msvcrt 모듈은 간단한 솔루션을 제공합니다.

import msvcrt

# Define variables
num = 0
done = False

# Infinite loop
while not done:
    # Print and increment number
    print(num)
    num += 1

    # Check for keyboard input
    if msvcrt.kbhit():
        # Display pressed key and quit
        pressed_key = msvcrt.getch()
        print("You pressed", pressed_key, "so now I will quit")
        done = True

termios 모듈 사용(Linux)

Linux 기반 콘솔 애플리케이션의 경우 termios 모듈은 다음과 같습니다. 활용:

import sys, select, tty, termios

# Define utility function to check for keyboard input
def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

# Configure terminal settings for non-blocking input
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())

# Infinite loop
num = 0
while 1:
    # Print and increment number
    print(num)
    num += 1

    # Check for keyboard input
    if isData():
        # Read single character from keyboard
        c = sys.stdin.read(1)
        # Check for escape key to quit
        if c == '\x1b':
            break

# Restore terminal settings
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

Pygame 모듈 사용(교차 플랫폼)

여러 플랫폼에 걸쳐 비차단 입력이 필요하거나 그래픽 사용자 인터페이스를 원하는 경우 Pygame은 다음을 제공합니다. 크로스 플랫폼 솔루션:

import pygame
from pygame.locals import *

# Define variables
num = 0
done = False

# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Python numbers')
screen.fill((159, 182, 205))
font = pygame.font.Font(None, 17)

# Infinite loop
while not done:
    # Display number
    display(str(num))
    num += 1

    # Check for events (e.g., keyboard input)
    pygame.event.pump()
    keys = pygame.key.get_pressed()

    # Check for escape key to quit
    if keys[K_ESCAPE]:
        done = True

위 내용은 Python 콘솔 애플리케이션에서 비차단 사용자 입력을 어떻게 구현할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.