使用多处理

时间:2016-10-05 16:20:40

标签: python serial-port multiprocessing

我有一个使用串口连接Arduino的python程序。我想实时绘制一些数据,而不会减慢执行速度,所以我尝试多处理。但是,我收到了错误

    serial.serialutil.SerialException: could not open port 'COM6': WindowsError(5, 'Access is denied.') # COM6 is the port connected to Arduino

令人惊讶的是,当多处理中的功能未运行时,Arduino之间的连接仍然存在。我的代码如下,

class ArduinoThread(threading.Thread):
    def __init__(self, portnum):
        threading.Thread.__init__(self)
        self.setName("Arduino")
        self.Arduino = serial.Serial(port="COM"+str(portnum), baudrate=19200)
    def run(self):
        # some function


def MyPlot_realtime(DATA):
    while True:
        data = DATA.get(False)
        plt.plot(data)


UNO = ArduinoThread(6)
UNO.start()

plt.ion()
pltQ = multiprocessing.Queue()
pltP = multiprocessing.Process(target=MyPlot_realtime, args=(pltQ,))
pltP.start()

while True:
    # some calculation on data
    UNO.update(data)

    if pltQ.empty():
        pltQ.put(data)

简单地评论多处理部分代码可以很好地工作。存在多处理时会弹出错误,但UNO.update(data)仍在工作,而MyPlt_realtime根本不工作。

(我的代码很复杂所以我简化了。我正在使用另一个串口连接另一台设备。我也在使用Tkinter。希望问题不是来自那些部分)

1 个答案:

答案 0 :(得分:0)

将主代码置于if条件中,如下所示:

if __name__ == '__main__':

我不知道为什么,但它解决了我的问题,大多数例子似乎都是这样做的。