如何读取键盘输入?

发布于 2024-10-25 12:15:35 字数 193 浏览 1 评论 0 原文

我想用Python从键盘读取数据。我尝试了这段代码:

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

但它不起作用,无论是在 Eclipse 还是在终端中,它总是停止问题。我可以输入一个数字,但什么也没发生。

你知道为什么吗?

I would like to read data from the keyboard in Python. I tried this code:

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

But it doesn't work, either with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen.

Do you know why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

↘紸啶 2024-11-01 12:15:35

则使用

input('Enter your input:')

如果您使用Python 3,

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

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

如果您使用Python 2,则需要使用raw_input而不是input

Use

input('Enter your input:')

if you use Python 3.

And if you want to have a numeric value, just convert it:

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

If you use Python 2, you need to use raw_input instead of input.

眉黛浅 2024-11-01 12:15:35

看来你在这里混合了不同的Python(Python 2.x vs. 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")

如果你想使用格式打印数字,在Python 3 str.format建议使用 ()

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

而不是:

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

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

It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)...
This is basically correct:

nb = input('Choose a number: ')

The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:

nb = raw_input('Choose a number: ')

If you want to convert that to a number, then you should try:

number = int(nb)

... though you need to take into account that this can raise an exception:

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

And if you want to print the number using formatting, in Python 3 str.format() is recommended:

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

Instead of:

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

But both options (str.format() and %) do work in both Python 2.7 and Python 3.

蓬勃野心 2024-11-01 12:15:35

非阻塞、多线程示例:

由于阻塞键盘输入(因为 input() 函数会阻塞)通常不是我们想要做的事情(我们经常会这样做)喜欢继续做其他事情),这里有一个非常精简的多线程示例来演示如何继续运行您的主应用程序,同时在键盘输入到达时仍然读取它们。我在我的 eRCaGuy_PyTerm 串行终端程序 此处(在代码中搜索 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
- https://stackoverflow.com/questions/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
输入字符串 = 7000
退出
input_str = 退出
退出串行终端。
结束。

Python Queue 库是线程安全的:

请注意,Queue.put()Queue.get() 以及其他 Queue 类方法都是线程安全的! (这与 C++ 标准模板库中的队列和其他容器不同!)由于 Python Queue 类及其方法是线程安全的,这意味着它们实现了交互所需的所有内部锁定语义。线程操作,因此队列类中的每个函数调用都可以被视为单个原子操作。请参阅文档顶部的注释: https://docs.python.org/ 3/library/queue.html(强调):

队列模块实现了多生产者、多消费者队列。 当必须在多个线程之间安全地交换信息时,它在线程编程中特别有用。此模块中的 Queue 类实现所有必需的锁定语义

参考文献:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html< /a>
  2. *****https://www.tutorialspoint.com/python/python_multithreading。 htm
  3. *****https://en.wikibooks.org/wiki/ Python_编程/线程
  4. Python:我该怎么做从超类创建子类?
  5. https://docs.python.org /3/library/queue.html
  6. https://docs.python. org/3.7/library/threading.html
  7. [我使用上面介绍的技术和代码的存储库] https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm

相关/交叉链接:

  1. [我的答案] PySerial非阻塞读取循环

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive. I use this technique in my eRCaGuy_PyTerm serial terminal program here (search the code for input()).

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

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. Same Python 3 code as above, but with extensive explanatory comments:

"""
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
- https://stackoverflow.com/questions/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()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are all thread-safe! (This is unlike queues and other containers in the standard template library in C++!) Since the Python Queue class and its methods are thread-safe, that means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html
  7. [My repo where I use the techniques and code presented above] https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm

Related/Cross-Linked:

  1. [my answer] PySerial non-blocking read loop
执笏见 2024-11-01 12:15:35

我来这里是为了寻找如何阅读单个字符。

我根据 readchar 库stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user">这个问题。 pip 安装后:

import readchar

key = readchar.readkey()

I came here looking for how to read a single character.

I found the readchar library, based on the answers to this question. After pip install:

import readchar

key = readchar.readkey()
笑红尘 2024-11-01 12:15:35

您可以通过使用变量来简单地使用 input() 函数。快速的例子!

user = input("Enter any text: ")
print(user)

you can simply use the input() function by using a variable. quick exemple!

user = input("Enter any text: ")
print(user)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文