pyserial与python上的大规模进程

时间:2016-06-03 19:52:09

标签: python pyserial

我在一个程序中使用Pyserial来创建一个带RS232的串行接口。它已经可以工作,但问题是我的设备,奴隶可以随时通信并解决我使用的代码

while(ser.inWaiting() == 0):
     #wait for some input the read it
     ser.readline()

问题在于我的CPU上的Python进程太庞大了。所以我的问题是:如果没有这个过程,我怎么能更“轻松”呢?

2 个答案:

答案 0 :(得分:0)

您可以使用线程。这是一个非常简单的例子:

#!/usr/bin/env python

import threading
import time
import sys

from subprocess import Popen, PIPE

import os

running = False

def Task1():
  time.sleep(5)
  count = 0
  while running:
    count += 1
    print "Task1 - count is", count
    time.sleep(3)

def Task2():
  while running:
    x = raw_input("Enter some text:")
    print "you entered:", x

def Task3():
  pipe = os.popen('./generate')
  while running:
    a = pipe.readline()
    a = a.strip('\n')
    print "Task3: ", a

t1 = threading.Thread(target = Task1, args=[])
t2 = threading.Thread(target = Task2, args=[])
t3 = threading.Thread(target = Task3, args=[])

running = True
# t2.start()
t1.start()
t3.start()

time.sleep(20)
print "=== exiting ==="
running = False
t1.join()
t3.join()
sys.exit(0)

generate计划就是(注意它使用-u):

#!/usr/bin/env python -u

import time
import sys

count = 0
while True:
  count += 1
  print "generate count is", count
  time.sleep(2)

答案 1 :(得分:0)

根据我的经验,PySerial太重了,无法传输大量数据。你最好放弃抽象和使用普通的系统调用。

在我的应用程序中,使用PySerial以50千字节的速度传输使用70-80%的i5-3550核心。稍后,使用普通tcsetattr()open()write()在C中重写的相同应用程序在Raspberry Pi中运行时没有明显(如在<1%中)CPU使用率。

即使在使用ostermios模块的Python上使用系统调用,甚至可能使用CTypes来调用cfsetospeed()cfsetispeed()也会提供大量的加速。