Converting Python3 - multithreading
I have some knowledge of Python 2.x. I am currently cleaning up the old code and converting it to Pyhton3. Clear writing and 2to3 made the most of it. I am struggling with multiple multi-threaded sections of 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 ends badly when run from Python 3.x: (run 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 went through all the python help / documentation, but it didn't help in clarity. Without rewriting most of the code (this is just a snippet), can anyone help me?
+3
source to share
No one has answered this question yet
See similar questions:
or similar: