简体   繁体   中英

how to run a class as a process in python

I tried to open several serial ports in python at the same time. I think it makes sense that every port as a class process, then I can group the respective properties and methods within this. Ok, I thought multiprocessing could be fine, but I have struggled to get it to work.

  1. Why can't I initialize the serial port in the init .

  2. When using super(serialManager, self) without the init the loop_starter is executed, but not as a process.

  3. super(serialManager, self).__init__(target=self.loop_starter,args=(serial_port, baudrate, timeout)) isn't executed, why?

how can I properly put all props in a class and process a method inside this class?

regards

from multiprocessing import Process
import serial
import time

class serialManager(Process):
    def __init__(self, serial_port, baudrate=57200, timeout=1):
        self.light = False
        self.ser = serial.Serial(serial_port, baudrate=baudrate, timeout=timeout)  #1
        #super(serialManager, self)  #2
        #self.loop_starter(serial_port, baudrate, timeout) #2
        super(serialManager, self).__init__(target=self.loop_starter,args=(serial_port, baudrate, timeout))  #3

    def loop_starter( self, serial_port, baudrate, timeout):  
        print("loop_iterator init")
        ser = serial.Serial(serial_port, baudrate=baudrate, timeout=timeout)
        self.loop(ser)

    def loop(self, ser):  
        self.light = not (self.light)
        values = bytearray([2, 82, 49, 4])
        ser.write(values)
        print("loop")
        time.sleep(2)

    #def run(self):
        #print('run')

def main():
    print("main")

if __name__ == "__main__":

    msm = serialManager("COM7")
    print ("inited")
    try:
        msm.start()
        print ("started")

        #while True:
            #main()
    except KeyboardInterrupt:
        print("caught in main")
    finally:
        msm.join()

        while True:
            main()
            time.sleep (1)

ok, I also tried this little script without success. why isnt the run executed?

from multiprocessing import Process

import time

class P(Process):
    def __init__(self):
        super(P, self).__init__()
    def run(self):
        print("run")
        #time.sleep(0.5)

def main():
    while True:
        print("main")
        time.sleep(2.5)

if __name__ == "__main__":
    p = P()
    p.start()
    p.join()
    main()

Your test script executes run() fine. Per the Process documentation :

If a subclass overrides the constructor, it must make sure it invokes the base class constructor (Process. init ()) before doing anything else to the process.

Your serialManager class is invoking super() at the end instead of the begining of __init__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM