我对Python 2.x有一些了解。我目前正在清理一些旧代码并将其转换为Pyhton3。一个清晰的写作和2to3做了大部分。我正在努力解决代码的一些多线程部分。
#!/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()
Python2中的一切都运行良好,但在使用Python 3.x执行时结果很糟糕: (启动脚本,然后按 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
我已经浏览了所有的python帮助/文档,但在清晰度方面没有帮助。如果没有重写大部分代码(它只是一个代码片段),有人可以帮助我吗?