当程序在python中运行时,如何防止用户输入控制台?

当程序在python中运行时,如何防止用户输入控制台?,python,console,Python,Console,我正在用python制作一个在控制台上运行的游戏。当我退出游戏时,我按下的所有键都会自动键入。我该如何阻止这种情况发生?此外,在使用input()函数时,我仍然希望有用户输入。顺便说一下,这是Windows上的 如果您想要代码,这也有同样的“问题”: 当程序在命令提示符下完成时,出现以下情况: C:\Users\User>awdsaawdsadwsaasdwaws 基本上,在代码运行时按下任何键。当其他东西也在命令提示符下运行时会发生这种情况,但我想知道如何在python中禁用它 编辑:

我正在用python制作一个在控制台上运行的游戏。当我退出游戏时,我按下的所有键都会自动键入。我该如何阻止这种情况发生?此外,在使用
input()
函数时,我仍然希望有用户输入。顺便说一下,这是Windows上的

如果您想要代码,这也有同样的“问题”:

当程序在命令提示符下完成时,出现以下情况:

C:\Users\User>awdsaawdsadwsaasdwaws
基本上,在代码运行时按下任何键。当其他东西也在命令提示符下运行时会发生这种情况,但我想知道如何在python中禁用它

编辑:我不断地挖掘,发现我要找的是刷新或清除键盘缓冲区。我将我的问题标记为另一个问题的副本,其中有一些答案,但这一个对我最有效:

def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios    #for linux/unix
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)

这是因为您的计算机在控制台上注册了按键笔划,这些笔划在
stdin
输入流中可用

如果将脚本保存为
test.py
并运行
python test.py
并开始输入一些击键,如
abc
,则这些字母将在标准输入中

您的脚本不会读取它们,因为它不会触及该流,因为您没有使用
input()
或任何其他将读取该流的调用。脚本完成后,字符仍在标准输入中,提示返回并读取这些字符,结果如下:

你好 你好 你好 PS C:\Users\username>abc 为了避免这种情况,可以在脚本末尾读取/刷新输入缓冲区。然而,如果您需要它在所有操作系统中以及在不同的脚本运行模式下(直接从cmd、IDLE、在其他ide中等)工作,那么这将非常困难

问题是,在您尝试读取标准输入流之前,无法知道标准输入流上是否有输入。但是,如果您尝试从中读取,脚本将暂停,直到收到“行结束”或“文件结束”。如果用户只是按了一下键,那就不会发生,所以你会一直读到他们按了Ctrl+Break或Ctrl+C之类的键

这是一种比较稳健的方式,但我建议您在您认为可能使用脚本的场景和环境中测试它:

import sys
import threading
import queue
import os
import signal

for _ in range(100000):
    print("Hello")

timeout = 0.1  # sec


def no_input():
    # stop main thread (which is probably blocked reading input) via an interrupt signal
    # only available for windows in Python version 3.2 or higher
    os.kill(os.getpid(), signal.SIGINT)
    exit()


# if a sigint is received, exit the main thread (you could call another function to do work first and then exit()
signal.signal(signal.SIGINT, exit)

# input is stored here, until it's dealt with
input_queue = queue.Queue()


# read all available input until main thread exit
def get_input():
    while True:
        try:
            # read input, not doing anything with it
            _ = input_queue.get(timeout=timeout)
        except queue.Empty:
            no_input()


reading_thread = threading.Thread(target=get_input)
reading_thread.start()

# main loop: put any available input in the queue, will wait for input if there is none
for line in sys.stdin:
    input_queue.put(line)

# wait for reading thread
reading_thread.join()
from subprocess import call
from os import name as os_name

call('clear' if os_name =='posix' else 'cls')
它基本上从第二个线程读取输入,允许主线程获取输入,并可能对其进行处理,直到什么都没有剩下,然后它只告诉主线程退出。请注意,这将导致脚本退出,退出代码为2,这可能不是您想要的

还请注意,您仍将在屏幕上看到输入,但它将不再传递给终端:

你好 你好 你好 abc PS C:\Users\username> 我不知道除了在Linux上执行类似于
stty-echo
的操作之外,是否有一种简单的方法可以避免回声。当然,您可以在脚本结束时调用系统以清除屏幕:

import sys
import threading
import queue
import os
import signal

for _ in range(100000):
    print("Hello")

timeout = 0.1  # sec


def no_input():
    # stop main thread (which is probably blocked reading input) via an interrupt signal
    # only available for windows in Python version 3.2 or higher
    os.kill(os.getpid(), signal.SIGINT)
    exit()


# if a sigint is received, exit the main thread (you could call another function to do work first and then exit()
signal.signal(signal.SIGINT, exit)

# input is stored here, until it's dealt with
input_queue = queue.Queue()


# read all available input until main thread exit
def get_input():
    while True:
        try:
            # read input, not doing anything with it
            _ = input_queue.get(timeout=timeout)
        except queue.Empty:
            no_input()


reading_thread = threading.Thread(target=get_input)
reading_thread.start()

# main loop: put any available input in the queue, will wait for input if there is none
for line in sys.stdin:
    input_queue.put(line)

# wait for reading thread
reading_thread.join()
from subprocess import call
from os import name as os_name

call('clear' if os_name =='posix' else 'cls')

如果您能提供一些代码,那就太好了,这样我们就不必猜测了。这似乎也不太可能,除非您的程序注册按下的键,然后在按下的每个键上循环,并使用python对其进行模拟。但是你会知道为什么会这样。好吧,根据我的推断(因为你还没有提供代码),我想说有一些打印语句可以打印用户使用
input()
输入的所有内容end@Matiiss控制台中的游戏是蛇游戏。当程序运行时,我希望用户可以使用
input()
更改设置。这就是为什么有输入。除此之外,当你死的时候,你按下的所有键都在下一行,就像我说的你应该提供代码一样。如果我不知道您在代码中添加了什么,您认为我将如何回答为什么会发生这种情况?