2014-02-07 63 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 
採取你的朋友 例