在键入python时打印

时间:2019-03-13 18:37:21

标签: python python-3.x input

我有一个小问题。您如何键入数字,并在键入时将其打印出来。例如

group by

但是这一直等到您按Enter键,然后执行打印工资。 我的意思是键入时,打印工资显示键入时的值。

1 个答案:

答案 0 :(得分:0)

使用键盘模块的解决方案

如果您想在使用模块键盘键入时打印出键盘输出,这是功能齐全的示例。您不能在IDLE中运行此命令,因为回车不起作用。可能有更简单的解决方案,但这是我脑海中可以想到的最好的解决方案。我使用了keyboard模块。

# Imports
import keyboard

# Create variables
salary = ""
pre = "Salary:"

# Print the pre-salary text to start off
print(pre, end="\r")

# The callback function
def myfunc(event):
    # Grab the global variables
    global salary
    global pre
    # The keypresses that you dont want to log
    forbidden = ["shift", "Alt", "ctrl", "esc", "left", "right", "up", "down"]
    # Exits the program when the key ENTER is pressed
    if event.name == "enter":
        print("\n")
        raise SystemExit
    # Simulates a delete by taking away the last character in the salary and carrige returning a ' '
    elif event.name == "backspace":
        salary = salary[:-1]
        print(pre, salary, ' ', end="\r")
    # Creates a space (Without this it would just log 'space'
    elif event.name == "space":
        salary += ' '
        print(pre, salary, ' ', end="\r")
    # Checks if the keypress is in the forbidden list
    elif event.name in forbidden:
        return
    else:
        # Add the keypress to the salary
        salary += event.name
        # Print it out using a carrige return
        print(pre, salary, end="\r")

# When a key is pressed call the function myfunc
# Suppressing the output will allow me to print it myself
keyboard.on_press(myfunc, suppress=True)

# Puts it into an infinite loop
keyboard.wait()