I have two processes which I want to communicate with each other:
file hwmgr.py:
import multiprocessing as mp
from setproctitle import setproctitle
import smbus
import myLoggingModule as log
class HWManager(mp.Process):
def __init__(self):
mp.Process.__init__(self)
self.i2c_lock = mp.Lock()
def run(self):
setproctitle('hwmgr')
# self.logger = log.config_logger(**kwargs)
def get_voltage(self):
with self.i2c_lock:
# ...do i2c stuff to get a voltage with smbus module
# self.logger.debug('Got a voltage: %s', voltage)
return voltage
file main.py:
import hwmgr
hwm = hwmgr.HWManager()
hwm.start()
battery = hwm.get_voltage()
print battery # Works!
So, interestingly, this works as expected - the voltage is returned by the method call without any special multiprocessing wizardry. However, if I enable the two lines involving the logger, when the logger.debug() call is encountered, I get:
AttributeError: 'HWManager' object has no attribute 'logger'
And, indeed, if I print a dir(self)
right about there, it doesn't have a logger
.
I don't get it?? Where did my logger go?
The reason the logger is defined in the run()
method, rather than __init__()
is because I'm after the root logger of the new process, and because the logger's file name is taken from the new process title (getproctitle()
) which can't be called until after the process has forked at completion of the __init__()
method -- there might be another way to do this part, of course, but I haven't found it yet...
WIP code:
I've removed the reference to the logging module - it doesn't matter what the attribute is.
If you comment out the line print houdiniAttribute
, everything works as expected
Just to be clear, the passing a return int works - the disappearing attribute is the concern
file hwmgr.py:
import multiprocessing as mp
from setproctitle import setproctitle
import smbus
class HWManager(mp.Process):
def __init__(self):
mp.Process.__init__(self)
self.i2c_lock = mp.Lock()
def run(self):
setproctitle('hwmgr')
self.houdiniAttribute = 'ASDFGHJKL'
with self.i2c_lock:
pass # Set up I2C bus to take ADC readings
while True: # Doesn't matter if this is here...
pass
def get_voltage(self):
with self.i2c_lock:
voltage = 12.0 # Actually, do i2c stuff to get a voltage with smbus module
print self.houdiniAttribute
return voltage
file client.py:
import multiprocessing as mp
from setproctitle import setproctitle
from time import sleep
class HWClient(mp.Process):
def __init__(self, hwm):
mp.Process.__init__(self)
self.hwm = hwm
def run(self):
setproctitle('client')
while True:
battery = self.hwm.get_voltage()
print battery
sleep(5)
file main.py:
import hwmgr
import client
hwm = hwmgr.HWManager()
hwm.start()
cl = client.HWClient(hwm)
cl.start()