Hướng dẫn python detect keyboard input - python phát hiện đầu vào bàn phím

Dưới đây là một giải pháp đa nền tảng, cả chặn và không chặn, không yêu cầu bất kỳ thư viện bên ngoài nào:

import contextlib as _contextlib

try:
    import msvcrt as _msvcrt

    # Length 0 sequences, length 1 sequences...
    _ESCAPE_SEQUENCES = [frozenset(("\x00", "\xe0"))]

    _next_input = _msvcrt.getwch

    _set_terminal_raw = _contextlib.nullcontext

    _input_ready = _msvcrt.kbhit

except ImportError:  # Unix
    import sys as _sys, tty as _tty, termios as _termios, \
        select as _select, functools as _functools

    # Length 0 sequences, length 1 sequences...
    _ESCAPE_SEQUENCES = [
        frozenset(("\x1b",)),
        frozenset(("\x1b\x5b", "\x1b\x4f"))]

    @_contextlib.contextmanager
    def _set_terminal_raw():
        fd = _sys.stdin.fileno()
        old_settings = _termios.tcgetattr(fd)
        try:
            _tty.setraw(_sys.stdin.fileno())
            yield
        finally:
            _termios.tcsetattr(fd, _termios.TCSADRAIN, old_settings)

    _next_input = _functools.partial(_sys.stdin.read, 1)

    def _input_ready():
        return _select.select([_sys.stdin], [], [], 0) == ([_sys.stdin], [], [])

_MAX_ESCAPE_SEQUENCE_LENGTH = len(_ESCAPE_SEQUENCES)

def _get_keystroke():
    key = _next_input()
    while (len(key) <= _MAX_ESCAPE_SEQUENCE_LENGTH and
           key in _ESCAPE_SEQUENCES[len(key)-1]):
        key += _next_input()
    return key

def _flush():
    while _input_ready():
        _next_input()

def key_pressed(key: str = None, *, flush: bool = True) -> bool:
    """Return True if the specified key has been pressed

    Args:
        key: The key to check for. If None, any key will do.
        flush: If True (default), flush the input buffer after the key was found.
    
    Return:
        boolean stating whether a key was pressed.
    """
    with _set_terminal_raw():
        if key is None:
            if not _input_ready():
                return False
            if flush:
                _flush()
            return True

        while _input_ready():
            keystroke = _get_keystroke()
            if keystroke == key:
                if flush:
                    _flush()
                return True
        return False

def print_key() -> None:
    """Print the key that was pressed
    
    Useful for debugging and figuring out keys.
    """
    with _set_terminal_raw():
        _flush()
        print("\\x" + "\\x".join(map("{:02x}".format, map(ord, _get_keystroke()))))

def wait_key(key=None, *, pre_flush=False, post_flush=True) -> str:
    """Wait for a specific key to be pressed.

    Args:
        key: The key to check for. If None, any key will do.
        pre_flush: If True, flush the input buffer before waiting for input.
        Useful in case you wish to ignore previously pressed keys.
        post_flush: If True (default), flush the input buffer after the key was
        found. Useful for ignoring multiple key-presses.
    
    Returns:
        The key that was pressed.
    """
    with _set_terminal_raw():
        if pre_flush:
            _flush()

        if key is None:
            key = _get_keystroke()
            if post_flush:
                _flush()
            return key

        while _get_keystroke() != key:
            pass
        
        if post_flush:
            _flush()

        return key

Bạn có thể sử dụng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
1 trong vòng một thời gian:

while True:
    time.sleep(5)
    if key_pressed():
        break

Bạn cũng có thể kiểm tra một khóa cụ thể:

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break

Tìm hiểu các khóa đặc biệt bằng cách sử dụng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
2:

>>> print_key()
# Press up key
\x00\x48

Hoặc đợi cho đến khi nhấn một khóa nhất định:

>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.

Bất kỳ giá trị nào bạn nhập vào

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 được lưu trữ dưới dạng chuỗi
>>> print_key()
# Press up key
\x00\x48
3. Bạn có thể xác nhận điều này bằng cách gọi
>>> print_key()
# Press up key
\x00\x48
4

Xem ví dụ dưới đây trong vỏ Python:Show

  • Số không có loại
    >>> print_key()
    # Press up key
    \x00\x48
    
    3. Vì vậy, chúng cần được chuyển đổi rõ ràng thành một loại số như
    >>> print_key()
    # Press up key
    \x00\x48
    
    6 hoặc
    >>> print_key()
    # Press up key
    \x00\x48
    
    7. Bạn cũng có thể kiểm tra loại biến số:
  • Làm thế nào để có được một số nguyên làm đầu vào của người dùng?
  • Làm thế nào để có được một số nguyên làm đầu vào của người dùng?
  • Đọc đầu vào dưới dạng phao
  • Đầu vào của người dùng Python và ví dụ về Eoferror
  • Ví dụ về lựa chọn đầu vào của người dùng Python
  • Xử lý ngoại lệ đầu vào
  • Raw_Input () - Phiên bản cũ

Trong Python 3 trở lên, bạn có thể sử dụng chức năng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3. Các phiên bản Python đã sử dụng hàm
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
4.

Sự khác biệt giữa các chức năng này là không, chỉ có tên phiên bản. Mặc dù nó có cùng một chức năng nhưng bạn nên sử dụng chức năng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3.

  • Vì vậy, thay vào đó:
  • Hàm
    while True:
        time.sleep(5)
        if key_pressed("\x00\x48"):  # Up arrow key on Windows.
            break
    
    4 đã được không dùng nữa và loại bỏ khỏi Python 3. Nếu bạn vẫn đang sử dụng phiên bản Python 2.x, bạn nên nâng cấp ngay bây giờ.
  • Sự kết luận

Khóa học liên quan: Khóa học & Bài tập lập trình Python hoàn chỉnh Complete Python Programming Course & Exercises

Chức năng cú pháp của đầu vào ()

Cú pháp của hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 là:

input("Your name: ")

Là tham số, nó lấy một chuỗi, được in trong thiết bị đầu cuối. Đây là một tham số tùy chọn, đôi khi được gọi là

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
6.
This is an optional parameter, sometimes called
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
6.

Tham số là một văn bản được in lên màn hình. Nếu chúng ta nói về văn bản, chúng ta nói chuỗi.

Bạn có thể in thông tin cho người dùng, tức là họ nên nhập giá trị nào.

Hàm đầu vào ():input() function:

  • Sử dụng hàm input () để lấy đầu vào người dùng python từ bàn phíminput() function to get Python user input from keyboard
  • Nhấn phím Enter sau khi nhập giá trị.
  • Chương trình chờ đợi đầu vào của người dùng một cách vô định, không có thời gian chờ.
  • Hàm đầu vào trả về một chuỗi, mà bạn có thể lưu trữ trong một biến
  • Kết thúc bằng Ctrl-D (UNIX) hoặc Ctrl-Z+Return (Windows)Ctrl-D (Unix) or Ctrl-Z+Return (Windows)

Nhận đầu vào của người dùng trong Python

Dưới đây là một ví dụ đơn giản để có đầu vào của người dùng và in nó trong thiết bị đầu cuối.

name = input("Enter a name: ")
print(name)

Hàm input () có đầu vào người dùng (bàn phím) và lưu trữ nó vào tên biến.input() function gets user input (keyboard) and stores it into variable name.

Đây là một biến. Hàm in () hiển thị nó với màn hình.name is a variable. The print() function shows it to the screen.

Người dùng phải nhấn phím Enter trong dòng lệnh. Sau đó, chuỗi đã nhập được gửi đến ứng dụng của bạn.

Vì vậy, để có được một giá trị văn bản, bạn có thể sử dụng hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 lấy làm một chuỗi được in.

Lưu ý: Don Tiết quên gán đầu vào cho một biến,

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
8. don’t forget to assign the input to a variable,
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
8.

Bạn có thể sử dụng đầu ra ưa thích được đặt tên là chuỗi được định dạng hoặc f-string. Để làm điều đó, đặt một

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
9 trước chuỗi và sử dụng dấu ngoặc xoăn để xuất biến của bạn:
To do that, put an
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
9 before the string and use curly brackets to output your variable:

name = input("Enter your name: ")
print(f"Your name is {name}")

Tóm tắt:

  • Hàm
    while True:
        time.sleep(5)
        if key_pressed("\x00\x48"):  # Up arrow key on Windows.
            break
    
    3 trả về một chuỗi. Điều này có thể được lưu trữ trong một biến (tên)
  • Biến sau đó được hiển thị đến màn hình bằng hàm
    >>> print_key()
    # Press up key
    \x00\x48
    
    1.
  • Bằng cách sử dụng các chuỗi được định dạng (F ở phía trước), bạn có thể trộn các biến với văn bản

Bây giờ bạn có thể cung cấp đầu vào bàn phím, nó sẽ được lưu trữ trong tên biến.

Khóa học liên quan: Khóa học & Bài tập lập trình Python hoàn chỉnh Complete Python Programming Course & Exercises

Loại trở lại

Bất kỳ giá trị nào bạn nhập vào

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 được lưu trữ dưới dạng chuỗi
>>> print_key()
# Press up key
\x00\x48
3. Bạn có thể xác nhận điều này bằng cách gọi
>>> print_key()
# Press up key
\x00\x48
4
You can confirm this by calling
>>> print_key()
# Press up key
\x00\x48
4

Xem ví dụ dưới đây trong vỏ Python:

>>> name = input("Enter name: ")
Enter name: Alice
>>> city = input("Enter city: ")
Enter city: Wellington
>>> type(name)
<class 'str'>
>>> type(city)
<class 'str'>
>>>

Số không có loại

>>> print_key()
# Press up key
\x00\x48
3. Vì vậy, chúng cần được chuyển đổi rõ ràng thành một loại số như
>>> print_key()
# Press up key
\x00\x48
6 hoặc
>>> print_key()
# Press up key
\x00\x48
7. Bạn cũng có thể kiểm tra loại biến số:

>>> x = 3
>>> y = 2.5
>>> type(x)
<class 'int'>
>>> type(y)
<class 'float'>
>>>

Làm thế nào để có được một số nguyên làm đầu vào của người dùng?

Nếu bạn gọi hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3, nó sẽ trả về văn bản đơn giản (chuỗi). Vì vậy, nếu bạn muốn sử dụng số nguyên, bạn phải chuyển đổi chuỗi thành int.integers, you have to convert the string to an int.

Để có được một số nguyên (toàn bộ số), bạn có thể làm điều này:

while True:
    time.sleep(5)
    if key_pressed():
        break
0

Nhận đầu vào người dùng số nguyên trên một dòng:integer user input on a single line:

while True:
    time.sleep(5)
    if key_pressed():
        break
1

Bạn có thể nhận được nhiều biến từ người dùng và sử dụng chúng trong chương trình của mình. Chương trình bên dưới có biến x và biến Y, sau đó tổng hợp và xuất chúng.
The program below gets variable x and variable y, and then sums and outputs them.

while True:
    time.sleep(5)
    if key_pressed():
        break
2

Hãy tính đến rằng nếu người dùng không thực sự nhập một số nguyên, mã này sẽ ném một ngoại lệ.

while True:
    time.sleep(5)
    if key_pressed():
        break
3

Vì vậy, hãy chắc chắn để nhập một số. Nếu bạn muốn ngăn chặn các ngoại lệ, hãy xem phần bên dưới Xử lý ngoại lệ đầu vào.

Đọc đầu vào dưới dạng phao

Để có được một số (không định nghĩa), giống như số điểm nổi, bạn có thể gọi phương thức

>>> print_key()
# Press up key
\x00\x48
9 để chuyển đổi chuỗi.

Một chiếc phao (điểm nổi) là một số như

>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
0,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
1,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
2,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
3, v.v.float (floating point) is a number like
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
0,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
1,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
2,
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
3 etc.

while True:
    time.sleep(5)
    if key_pressed():
        break
4

Đầu vào phải là một điểm nổi, bất kỳ đầu vào nào khác sẽ ném một ngoại lệ. Xem Xử lý ngoại lệ đầu vào.

Đầu vào của người dùng Python và ví dụ về Eoferror

Chương trình có thể có một eoferror. Ngoại lệ này được nêu ra nếu hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 không đọc bất kỳ dữ liệu nào. Điều này sẽ không được ném bởi một khóa nhập đơn giản, nhưng bằng cách làm gián đoạn chương trình với
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
5.EOFError. This exception is raised if the
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 function did not read any data.
This will not be thrown by a simple enter key, but by interrupting the program with
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
5.

Nếu bạn có một chương trình như thế này:

while True:
    time.sleep(5)
    if key_pressed():
        break
5

Bạn có thể làm gián đoạn chương trình bằng cách nhấn

>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
6 (EOF). Điều đó làm tăng một eoferror và chấm dứt kịch bản.

while True:
    time.sleep(5)
    if key_pressed():
        break
6

Ví dụ về lựa chọn đầu vào của người dùng Python

Bạn có thể xây dựng hệ thống đầu vào trắc nghiệm. Trước khi nhận đầu vào bàn phím bằng cách gọi hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3.
First get the keyboard input by calling the
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3 function.

Sau đó, bạn có thể đánh giá sự lựa chọn bằng cách sử dụng cấu trúc if-elif-else.

Lưu ý: Biểu tượng

>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
8 kiểm tra cho sự bình đẳng. Python nhạy cảm trường hợp.case-sensitive.

while True:
    time.sleep(5)
    if key_pressed():
        break
7

Điều quan trọng là sử dụng 4 không gian với mỗi thụt lề, không phải các tab và không phải là một lượng không gian khác nhau.

Xử lý ngoại lệ đầu vào

Nếu người dùng nhập vào đầu vào không hợp lệ hoặc đầu vào không hợp lệ, Python có thể ném một ngoại lệ. Để xử lý việc này, bạn có thể sử dụng mã bên dưới:

while True:
    time.sleep(5)
    if key_pressed():
        break
8

Raw_Input () - Phiên bản cũ

Trong Python 3 trở lên, bạn có thể sử dụng chức năng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3. Các phiên bản Python đã sử dụng hàm
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
4.
Older versions of Python used the
while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
4 function.

while True:
    time.sleep(5)
    if key_pressed():
        break
9

Sự khác biệt giữa các chức năng này là không, chỉ có tên phiên bản. Mặc dù nó có cùng một chức năng nhưng bạn nên sử dụng chức năng

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
3.

Vì vậy, thay vào đó:

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
0

Hàm

while True:
    time.sleep(5)
    if key_pressed("\x00\x48"):  # Up arrow key on Windows.
        break
4 đã được không dùng nữa và loại bỏ khỏi Python 3. Nếu bạn vẫn đang sử dụng phiên bản Python 2.x, bạn nên nâng cấp ngay bây giờ.
If you are still on a Python 2.x version, you should upgrade now.

Sự kết luận

Bạn có thể lấy đầu vào của người dùng với hàm input ().Điều này chờ đợi đầu vào bàn phím vô định.Nếu bạn thêm một tham số, nó sẽ in văn bản đó trước khi người dùng nhập.input() function. This waits for keyboard input indefinetly. If you add a parameter, it will print that text before the user input.

Bạn cũng đã thấy cách xử lý đầu vào không hợp lệ và biết về sự khác biệt giữa Python 2 và Python 3 (và mới hơn).

Nếu bạn chưa quen với Python, tôi đề nghị khóa học dưới đây.

Khóa học liên quan: Khóa học & Bài tập lập trình Python hoàn chỉnh Complete Python Programming Course & Exercises

Tải xuống bài tập