如何阅读键盘输入?


123

我想从python的键盘中读取数据

我尝试这样:

nb = input('Choose a number')
print ('Number%s \n' % (nb))

但是,无论是日食还是终端,它都不起作用,这始终是问题的解决之道。我可以输入数字,但是什么都没发生。

你知道为什么吗?


12
我很确定OP只是在输入数字后忘记按回车键,而且没有答案能真正回答问题。
阿兰·菲

Answers:


127

尝试

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

如果您想要一个数值,只需将其转换为:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

2
非阻塞多线程版本,因此您可以继续做而不是阻塞键盘输入:stackoverflow.com/a/53344690/4561887
Gabriel Staples

84

似乎您在这里混合使用不同的Python(Python 2.x与Python 3.x)...这基本上是正确的:

nb = input('Choose a number: ')

问题在于它仅在Python 3中受支持。正如@sharpner回答的那样,对于旧版本的Python(2.x),必须使用以下函数raw_input

nb = raw_input('Choose a number: ')

如果要将其转换为数字,则应尝试:

number = int(nb)

...尽管您需要考虑到这可能引发异常:

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

如果要使用格式打印数字,str.format()建议在Python 3 中进行:

print("Number: {0}\n".format(number))

代替:

print('Number %s \n' % (nb))

但是两个选项(str.format()%)在Python 2.7和Python 3中都可以使用。


1
space如果和平,请务必在用户输入的字符串后加上一个后缀,以供用户输入其输入内容。Enter Tel12340404VS Enter Tel: 12340404。看到!:P
梅拉德,2014年

做完了 谢谢你的建议。
2014年

15

非阻塞,多线程示例:

由于阻塞键盘输入(由于input()功能块)通常不是我们想要做的(我们经常想继续做其他事情),所以这是一个精简的多线程示例以演示如何保持运行。主要应用程序,同时还在到达时仍在读取键盘输入

通过创建一个在后台运行的线程,不断调用input(),然后将接收到的所有数据传递到队列中,可以实现这一目的。

这样,您的主线程就可以做任何想做的事情,只要队列中有东西,它就会从第一个线程接收键盘输入数据。

1.裸Python 3代码示例(无注释):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break

            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2.与上述相同的Python 3代码,但带有大量说明性注释:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- /programming/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()

        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop

            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 

    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

样本输出:

$ python3 read_keyboard_input.py
准备好进行键盘输入:

input_str =嘿
你好
input_str =你好
7000
input_str = 7000
exit
input_str = exit
退出串行终端。
结束。

参考文献:

  1. https://pyserial.readthedocs.io/zh-CN/latest/pyserial_api.html
  2. ***** https://www.tutorialspoint.com/python/python_multithreading.htm
  3. ***** https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python:如何从超类中生成子类?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

相关/交叉链接:

  1. PySerial非阻塞读取循环

4

input([prompt])eval(raw_input(prompt))从python 2.6开始等效并可用

由于不安全(由于评估),因此对于关键应用程序应首选raw_input。


1
+1代表那条有趣的信息,尽管我在举报该问题是因为它确实值得一提,作为对问题或答案的评论列出,因为它本身并不是真正的答案。
ArtOfWarfare 2014年

3
它也仅适用于Python2.x。在Python 3.x中。raw_input被重命名为input,并且不进行评估。
詹森·S

1
这不能为问题提供答案。要批评或要求作者澄清,请在其帖子下方发表评论。
埃里克·斯坦

@EricStein-我的标志被拒绝了,经过一番思考,我同意我太匆忙地进行了标志。看到这一点:meta.stackexchange.com/questions/225370/...
ArtOfWarfare

4

这应该工作

yourvar = input('Choose a number: ')
print('you entered: ' + yourvar)

7
这与其他答案所暗示的input()有何不同?
大卫·马科贡
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.