python3读取键盘输入_如何读取键盘输入?

无阻塞、多线程示例:

由于键盘输入上的阻塞(因为input()功能块)经常是而不是我们想做的事情(我们经常想继续做其他的事情),这里有一个非常简单的多线程示例来演示如何在每次读取键盘输入的同时继续运行主应用程序他们到达了。

其工作原理是创建一个线程在后台运行,不断调用input(),然后将接收到的任何数据传递给队列。

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

一。裸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。与上面的Python3代码相同,但有大量的解释性注释:"""

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

Ready for keyboard input:

hey

input_str = hey

hello

input_str = hello

7000

input_str = 7000

exit

input_str = exit

Exiting serial terminal.

End.

参考文献:

相关/交叉链接:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值