3

I have some knowledge of Python 2.x. I am currently cleaning up some old code and converting it to Pyhton3. A clear writing and 2to3 did most of it. I am struggling with some multi-thread section of the code.

#!/usr/bin/env python3
# coding=utf-8

import signal
import psutil
import threading
import time

class PingThread(threading.Thread):
    """Report server health"""

    def __init__(self):
        """Prepare the thread"""

        super(PingThread, self).__init__()
        self._stop = threading.Event()


    def stop(self):
        """When stop signal is given, stop gracefully"""

        self._stop.set()

    def stopped(self):
        """Check up the stop signal was given"""

        return self._stop.is_set()

    def ping_server(self):
        """Ping the health server

        :return: Number of threads
        :rtype: int
        """

        p = psutil.Process()
        threads = p.num_threads()

        #cnxn = pyodbc.connect(config.sql_connection)
        #cursor = cnxn.cursor()
        #cursor.execute('INSERT INTO pingtable (stamp, threads, cpu, memory) VALUES (getdate(), ?, ?, ?);', threads, p.cpu_percent(interval=None), p.memory_percent())
        #cnxn.commit()
        #cnxn.close()

        return threads

    def run(self):
        """Start the health monitoring"""

        while not self.stopped():
            print('\033[0;35mServer\033[0m: Reporting health (\033[4;37m' + str(self.ping_server()) + '\033[0m)')
            looped = 0
            while (not self.stopped()) and (looped < 1800):
                looped += 1
                time.sleep(1)

def signal_handler(signum, frame):
    """Signal handle to accept graceful Termination signal.

    :param signum: signal number
    :type signum: int
    :param frame: current stack frame
    :type frame: None or object
    """

    print('\n\033[0;35mServer\033[0m: Stopping with signal ' + str(signum) + '.')


"""Main. Start the threaded server."""

signal.signal(signal.SIGINT, signal_handler)
if __name__ == '__main__':

    pingThread = PingThread()
    print('\033[0;35mServer\033[0m: Starting daemon.')
    pingThread.start()
    signal.pause()
    pingThread.stop()

Everything works well in Python2, but end badly when executed with Python 3.x: (start the script, then press Ctrl + C)

Server: Starting daemon.
Server: Reporting health (2)
^C
Server: Stopping with signal 2.
Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown
    t.join()
  File "/usr/lib/python3.4/threading.py", line 1060, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.4/threading.py", line 1078, in _wait_for_tstate_lock
    self._stop()
TypeError: 'Event' object is not callable

I have been through all the python help/documentation but it's not help in term of clarity. Without rewriting to much of the code (it's only a snippet) can someone help me?

Python123
  • 31
  • 2

0 Answers0