Python Forum

Full Version: call method in class using threads?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi python-Volks,

I'm a phyton n00b trying to extend an existing program and I got stuck. Let me
try to explain very briefly the project to illustrate my problem:

1. My program's main loop is basically an event queue waiting for events
2. before this loop, a class "engine" and "time" is called

main.py:
engine = motor()
time = clock()
<set up the rest>
while True
        try:
                event = evt_queue.get()
        except queue.Empty:
                pass
        else:
        <EVENTS BEING PROCESSED>
motor.py:
class motor(object):
        def __init__(self):
                self._receiving_thread
                self._receiving_thread.daemon = True
                self.spawn(self)
        def spawn(self, engine):
                self.engine = engine
                self.process = subprocess.Popen(TELNET CONNECTION)
        def _receiving_thread_target
                while self.is_alive:
                        line = self.process.stdout.readline()
                        if not line:
                                continue
                        self.on_line_received(line)

        def wline(self,string)
                self.process.stdin.write(string)
        def on_line_received(self,buff)
                <process buff>
                fire event in queue
time.py:
class clock(object):
        <this basically runs a threaded real-time clock and is interfaced
         to some hardware which provides a time string using hw_clock_time>

        def hw_clock_time:
                ctime = copy.copy(self.hwclock.time)
                return ctime
This latter method hw_clock_time is called from outside time.py by
other events of the main loop.

My problem is now this:
I want to set the time via hw_clock_time
by sending a command to the telnet connection and
receiving a specific line to return as ctime.

For now I did that by defining a "global" variable (teltime) in the "motor" class and
letting the line-parser (on_line_received) modify this global.
        def hw_clock_time:
                fire(Event.wline("get telnet time")
                if not teltime = None:
                        return teltime
Even though this technically works, this raises timing issues,
as the telnet connection may not respond fast enough to catch the time update and the clock is ticking...
And apart from that: "globals" are considered evil by most python-guys I heard?

As a second attempt, I tried to call wline from inside hw_clock_time but I fail to do so without reinistantiating "engine", which opens a new telnet connection thread each time this is done - which is not what I want.

I guess there is a simple solution to my problem which I simply do not see?


Thanks in advance and best regards

Masterofamn