2014-02-07 22 views
1

我写一个python应用程序,读取(从控制台)用户输入Python从控制台和串口同时检查输入?

buff = raw_input('Enter code: ') 

,生成并基于一系列算法的输出。

我遇到的问题是应用程序是也通过串行连接到另一台机器,设置一些状态配置属性。 要阅读我使用PySerial库从串行端口(COM)的字符串:

ser = serial.Serial('/dev/ttyAMA0') 
ser.baudrate = 115200 
[...] 
if not(ser.isOpen()): 
    ser.open() 
s = ser.readline() 

我怎样才能在同一时间检查两个输入端? raw_input()停止程序的执行,直到提交一个字符串,因此阻止检查是否在此期间通过串口发送了某些内容。同样的事情适用于等待串行输入。

我想避免多线程(代码在RaspberryPi上运行),因为它可能会增加过多的复杂度。

谢谢! MJ

回答

3

选择是从here

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 
采取你的朋友 例