问题描述
我写了一个python应用程序读取用户输入(从控制台)
I am writing a python application that reads the user input (from the console):
buff = raw_input('Enter code: ')
,并根据一系列算法生成和输出。
and generates and output based on a series of algorithms.
我遇到的问题是应用程序也通过串行连接到另一台设置一些状态配置属性的机器。
要从串口(COM)端口读取一个字符串,我使用的是PySerial库:
The problem I have is that the application is also connected via serial to another machine that sets some state configuration attributes.To read a string from the serial (COM) port I'm using the PySerial library:
ser = serial.Serial('/dev/ttyAMA0')
ser.baudrate = 115200
[...]
if not(ser.isOpen()):
ser.open()
s = ser.readline()
同时? raw_input()停止程序的执行,直到一个字符串提交,因此防止检查在这段时间是否通过串口发送。同样的情况也适用于等待串口输入。
How can I check both inputs at the same time ? raw_input() stops the execution of the program until a string is submitted hence preventing to check if during that time something is being sent over the serial port. Same thing applies when waiting for input from the serial.
我想避免多线程(代码运行在 RaspberryPi 因为它可能会增加过高的复杂性。
I would like to avoid multi-threading (the code is running on a RaspberryPi) as it would probably add an excessive level of complexity.
谢谢!
mj
THANKS!mj
推荐答案
选择是您的朋友
从
import sys
import select
import time
# files monitored for input
read_list = [sys.stdin]
# select() should wait for this many seconds for input.
# A smaller number means more cpu usage, but a greater one
# means a more noticeable delay between input becoming
# available and the program starting to work on it.
timeout = 0.1 # seconds
last_work_time = time.time()
def treat_input(linein):
global last_work_time
print("Workin' it!", linein, end="")
time.sleep(1) # working takes time
print('Done')
last_work_time = time.time()
def idle_work():
global last_work_time
now = time.time()
# do some other stuff every 2 seconds of idleness
if now - last_work_time > 2:
print('Idle for too long; doing some other stuff.')
last_work_time = now
def main_loop():
global read_list
# while still waiting for input on at least one file
while read_list:
ready = select.select(read_list, [], [], timeout)[0]
if not ready:
idle_work()
else:
for file in ready:
line = file.readline()
if not line: # EOF, remove file from input list
read_list.remove(file)
elif line.rstrip(): # optional: skipping empty lines
treat_input(line)
try:
main_loop()
except KeyboardInterrupt:
pass
这篇关于Python同时从控制台和串口检查输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!