def __init__(self, monitor = False, incoming_folder = None, processed_folder = None, incoming_callback = None, localinit = False, loglocation = "/var/log/", ConfigFilePath = None, start = True): self.Monitor = monitor # true if we receive IMAP email self.IncomingFolder = incoming_folder # folder to look for incoming email self.ProcessedFolder = processed_folder # folder to move mail to once processed self.IncomingCallback = incoming_callback # called back with mail subject as a parameter if ConfigFilePath == None: self.ConfigFilePath = "/etc/" else: self.ConfigFilePath = ConfigFilePath self.Mailbox = 0 self.EmailSendQueue = [] # queue for email to send self.DisableEmail = False self.DisableIMAP = False self.DisableSNMP = False self.SSLEnabled = False self.Threads = {} # Dict of mythread objects # log errors in this module to a file if localinit == True: self.logfile = "mymail.log" self.configfile = "mymail.conf" else: self.logfile = loglocation + "mymail.log" self.configfile = self.ConfigFilePath + "mymail.conf" self.log = mylog.SetupLogger("mymail", self.logfile) self.GetConfig() if self.DisableEmail: self.DisableIMAP = True self.DisableSNMP = True self.Monitor = False if not len(self.SMTPServer): self.DisableSNMP = True if not len(self.IMAPServer): self.DisableIMAP = True self.Monitor = False atexit.register(self.Close) if not self.DisableEmail: if not self.DisableSMTP and self.SMTPServer != "": self.Threads["SendMailThread"] = mythread.MyThread(self.SendMailThread, Name = "SendMailThread", start = start) else: self.LogError("SMTP disabled") if not self.DisableIMAP and self.Monitor and self.IMAPServer != "": # if True then we will have an IMAP monitor thread if incoming_callback and incoming_folder and processed_folder: self.Threads["EmailCommandThread"] = mythread.MyThread(self.EmailCommandThread, Name = "EmailCommandThread", start = start) else: self.FatalError("ERROR: incoming_callback, incoming_folder and processed_folder are required if receive IMAP is used") else: self.LogError("IMAP disabled")
def StartCommonThreads(self): self.Threads["CheckAlarmThread"] = mythread.MyThread(self.CheckAlarmThread, Name = "CheckAlarmThread") # start read thread to process incoming data commands self.Threads["ProcessThread"] = mythread.MyThread(self.ProcessThread, Name = "ProcessThread") if self.EnableDebug: # for debugging registers self.Threads["DebugThread"] = mythread.MyThread(self.DebugThread, Name = "DebugThread") # start thread for kw log self.Threads["PowerMeter"] = mythread.MyThread(self.PowerMeter, Name = "PowerMeter")
def __init__(self, updatecallback, address = 0x9d, name = "/dev/serial", rate=9600, loglocation = "/var/log/", inputfile = None): super(ModbusFile, self).__init__(updatecallback = updatecallback, address = address, name = name, rate = rate, loglocation = loglocation) self.Address = address self.Rate = rate self.PortName = name self.InputFile = inputfile self.InitComplete = False self.UpdateRegisterList = updatecallback self.RxPacketCount = 0 self.TxPacketCount = 0 self.ComTimoutError = 0 self.TotalElapsedPacketeTime = 0 self.ComTimoutError = 0 self.CrcError = 0 self.SimulateTime = True self.ModbusStartTime = datetime.datetime.now() # used for com metrics self.Registers = {} if self.InputFile == None: self.InputFile = os.path.dirname(os.path.realpath(__file__)) + "/modbusregs.txt" # log errors in this module to a file self.log = mylog.SetupLogger("mymodbus", loglocation + "mymodbus.log") if not os.path.isfile(self.InputFile): self.LogError("Error: File not present: " + self.InputFile) self.CommAccessLock = threading.RLock() # lock to synchronize access to the serial port comms self.UpdateRegisterList = updatecallback self.ReadInputFile(self.InputFile) self.Threads["ReadInputFileThread"] = mythread.MyThread(self.ReadInputFileThread, Name = "ReadInputFileThread")
def __init__(self, name, callback = None, Reuse = False, log = None, simulation = False, nullpipe = False): super(MyPipe, self).__init__(simulation = simulation) self.log = log self.BasePipeName = name self.NullPipe = nullpipe if self.Simulation: return self.ThreadName = "ReadPipeThread" + self.BasePipeName self.Callback = callback self.FileAccessLock = threading.RLock() self.FileName = os.path.dirname(os.path.realpath(__file__)) + "/" + self.BasePipeName + "_dat" try: if not Reuse: try: os.remove(self.FileName) except: pass with open(self.FileName, 'w') as f: # create empty file f.write("") except Exception as e1: self.LogErrorLine("Error in MyPipe:__init__: " + str(e1)) if self.NullPipe or not self.Callback == None or not self.Simulation: self.Threads[self.ThreadName] = mythread.MyThread(self.ReadPipeThread, Name = self.ThreadName)
def StartReadThread(self): # start read thread to monitor incoming data commands self.Threads["SerialReadThread"] = mythread.MyThread( self.ReadThread, Name="SerialReadThread") return self.Threads["SerialReadThread"]
def __init__(self, apikey, location, log=None, unit='imperial'): super(MyWeather, self).__init__() self.APIKey = apikey self.log = log self.Location = location self.OWM = None self.Observation = None self.WeatherUnit = unit self.WeatherData = None self.ObservationLocation = None self.DataAccessLock = threading.Lock( ) # lock to synchronize access to WeatherData if not pyowm_installed: self.LogError( "Library pyowm not installed, disabling weather support.") return try: if self.APIKey != None: self.APIKey = self.APIKey.strip() if self.Location != None: self.Location = self.Location.strip() if self.APIKey == None or not len( self.APIKey) or self.Location == None or not len( self.Location): self.LogError( "Weather API key invalid or Weather Location invalid") return self.InitOWM() self.Threads["WeatherThread"] = mythread.MyThread( self.WeatherThread, Name="WeatherThread") except Exception as e1: self.LogErrorLine("Error on MyWeather:init: " + str(e1))
def start_data(): # 創建線程通訊 t = mythread.MyThread(func=udp_conn.udp_start) t.start() t.join() udp_res = t.get_result() if udp_res == 'OK': return 'ok' else: return 'error'
def stop_data(): # 創建線程通訊 t = mythread.MyThread(func=udp_conn.udp_stop) t.start() t.join() udp_res = t.get_result() if udp_res == 'OK': sql = "delete from InstWheel" c.execute(sql) return 'ok' else: return 'error'
def GetAuthorsdromLink(self, ses, link, idlist): s2 = ses.get(link) # 进入文章页面 # fout = open('output4.html', 'w',encoding="UTF-8") # fout.write(s2.text) soup2 = BeautifulSoup(s2.text, 'html.parser') atitles_list = soup2.find('section', id='authorlist') if not atitles_list: return None atitles = atitles_list.find_all('a', title='Show Author Details') if not atitles: atitles = atitles_list.find_all('a', title='显示作者详情') sum = 0 authors = [] threads = [] for atitle in atitles: authorId = re.findall(r'authorId=\w+&', atitle['href'])[0].replace( 'authorId=', '').replace('&', '') sum += 1 if authorId not in idlist: idlist.append(authorId) # print('第'+str(sum)+'作者') try: t = mythread.MyThread(ses, authorId, sum) threads.append(t) # author=t.get_result() # # author= self.crawel(ses, authorId, sum) except requests.exceptions.ReadTimeout: continue # if author: # authors.append(author) for t in threads: try: t.setDaemon(True) t.start() # author= self.crawel(ses, authorId, sum) except requests.exceptions.ReadTimeout: continue for t in threads: t.join() for t in threads: author = t.get_result() if author: printresult(author) authors.append(author) return authors
def __init__(self, updatecallback, address = 0x9d, name = "/dev/serial", rate=9600, config = None, inputfile = None): super(ModbusFile, self).__init__(updatecallback = updatecallback, address = address, name = name, rate = rate, config = config) self.Address = address self.Rate = rate self.PortName = name self.InputFile = inputfile self.InitComplete = False self.UpdateRegisterList = updatecallback self.RxPacketCount = 0 self.TxPacketCount = 0 self.ComTimoutError = 0 self.TotalElapsedPacketeTime = 0 self.ComTimoutError = 0 self.CrcError = 0 self.SimulateTime = True self.ModbusStartTime = datetime.datetime.now() # used for com metrics self.Registers = {} self.Strings = {} self.FileData = {} if self.InputFile == None: self.InputFile = os.path.dirname(os.path.realpath(__file__)) + "/modbusregs.txt" if not os.path.isfile(self.InputFile): self.LogError("Error: File not present: " + self.InputFile) self.CommAccessLock = threading.RLock() # lock to synchronize access to the serial port comms self.UpdateRegisterList = updatecallback if not self.ReadInputFile(self.InputFile): self.LogError("ModusFile Init(): Error loading input file: " + self.InputFile) else: self.Threads["ReadInputFileThread"] = mythread.MyThread(self.ReadInputFileThread, Name = "ReadInputFileThread") self.InitComplete = False
def __init__(self, apikey, location, log=None, unit='imperial'): super(MyWeather, self).__init__() self.APIKey = apikey self.log = log self.Location = location self.OWM = None self.Observation = None self.WeatherUnit = unit self.WeatherData = None self.ObservationLocation = None self.DataAccessLock = threading.Lock( ) # lock to synchronize access to WeatherData if not pyowm_installed: self.LogError( "Library pyowm not installed, disabling weather support.") return self.InitOWM() self.Threads["WeatherThread"] = mythread.MyThread(self.WeatherThread, Name="WeatherThread")
return 1 return n * fact(n - 1) def sumn(n): time.sleep(0.05) if n == 1: return 1 else: return n + sumn(n - 1) if __name__ == '__main__': fun_list = [fib, fact, sumn] print("main is starting at:", time.ctime()) n = 15 for i in range(len(fun_list)): print(fun_list[i](n)) print("signal thread done at:", time.ctime()) print("multi thread start at:", time.ctime()) threads = [] for i in range(len(fun_list)): t = mythread.MyThread(fun_list[i], (n, ), fun_list[i].__name__) threads.append(t) t.start() for i in range(len(fun_list)): threads[i].join() print(threads[i].getResult()) print("all done at:", time.ctime())
def timerThread(self, amount): print "Controller: timerThread being initialized" rt = mythread.MyThread(self.timerResetValue, 1, self.model.changeTimer, 1) # it auto-starts, no need of rt.start()
# thread.py from time import sleep import mythread import datetime def hello(name): #sleep(2) print "Hello %s! The time is %s" % (name,datetime.datetime.now()) print "starting..." print datetime.datetime.now() rt = mythread.MyThread(1, hello, "World") # it auto-starts, no need of rt.start() try: sleep(3) # your long-running job goes here... finally: rt.stop() # better in a try/finally block to make sure the program ends!
def __init__(self, host="127.0.0.1", port=9082, log=None, onready=None, onexercise=None, onrun=None, onrunmanual=None, onalarm=None, onservice=None, onoff=None, onmanual=None, onutilitychange=None): super(GenNotify, self).__init__() self.AccessLock = threading.Lock() self.Threads = {} self.LastEvent = None self.LastOutageStatus = None self.Events = {} # Dict for handling events if log != None: self.log = log else: # log errors in this module to a file self.log = mylog.SetupLogger("client", "/var/log/myclient.log") self.console = mylog.SetupLogger("notify_console", log_file="", stream=True) try: # init event callbacks if onready != None: self.Events["READY"] = onready if onexercise != None: self.Events["EXERCISING"] = onexercise if onrun != None: self.Events["RUNNING"] = onrun if onrunmanual != None: self.Events["RUNNING-MANUAL"] = onrunmanual if onalarm != None: self.Events["ALARM"] = onalarm if onservice != None: self.Events["SERVICEDUE"] = onservice if onoff != None: self.Events["OFF"] = onoff if onmanual != None: self.Events["MANUAL"] = onmanual if onutilitychange != None: self.Events["OUTAGE"] = onutilitychange startcount = 0 while startcount <= 10: try: self.Generator = myclient.ClientInterface(host=host, log=log) break except Exception as e1: startcount += 1 if startcount >= 10: self.console.info("genmon not loaded.") sys.exit(1) time.sleep(1) continue # start thread to accept incoming sockets for nagios heartbeat self.Threads["PollingThread"] = mythread.MyThread( self.MainPollingThread, Name="PollingThread") except Exception as e1: self.LogErrorLine("Error in mynotify init: " + str(e1))
# @login def server(): from config import setting phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) phone.bind((setting.HOST, setting.PORT)) phone.listen(setting.MAX_SOCKET_LISTEN) print('>>>') while True: conn, client_addr = phone.accept() t = pool.get_thread() #使用线程对象创建线程 obj = t(target=Communication, args=( pool, conn, )) obj.start() # 启动线程 phone.close() if __name__ == '__main__': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) pool = mythread.MyThread() server()
def __init__(self, port="/dev/ttyAMA0", rate=115200, loglocation="/var/log/", log=None, localinit=False, ConfigFilePath=None, recipient=None): super(MyModem, self).__init__() self.MessagesSent = 0 self.Errors = 0 self.SendActive = False self.ModemLock = threading.RLock() self.Sending = False self.SendQueue = [] if ConfigFilePath == None: self.ConfigFilePath = "/etc/" else: self.ConfigFilePath = ConfigFilePath # log errors in this module to a file if localinit == True: self.configfile = "mymodem.conf" else: self.configfile = self.ConfigFilePath + "mymodem.conf" # log errors in this module to a file if log == None: self.log = mylog.SetupLogger("mymodem", loglocation + "mymodem.log") else: self.log = log self.console = mylog.SetupLogger("mymodem_console", log_file="", stream=True) try: self.config = myconfig.MyConfig(filename=self.configfile, section="MyModem", log=self.log) if self.config.HasOption('log_at_commands'): self.LogAtCommands = self.config.ReadValue('log_at_commands', return_type=bool) else: self.LogAtCommands = False if self.config.HasOption('message_level'): self.MessageLevel = self.config.ReadValue('message_level') else: self.MessageLevel = "error" if self.config.HasOption('rate'): self.Rate = self.config.ReadValue('rate', return_type=int) else: self.Rate = rate if self.config.HasOption('port'): self.Port = self.config.ReadValue('port') else: self.Port = port if self.config.HasOption('recipient'): self.Recipient = self.config.ReadValue('recipient') else: self.Recipient = recipient if self.config.HasOption('modem_type'): self.ModemType = self.config.ReadValue('modem_type') else: self.ModemType = modem_type except Exception as e1: self.LogErrorLine("Error reading config file: " + str(e1)) self.LogConsole("Error reading config file: " + str(e1)) return # rate * 10 bits then convert to MS self.CharacterTimeMS = (((1 / self.Rate) * 10) * 1000) self.InitComplete = False try: self.SerialDevice = myserial.SerialDevice(port, rate=rate, loglocation=loglocation, log=self.log) self.Threads = self.MergeDicts(self.Threads, self.SerialDevice.Threads) self.Threads["SendMessageThread"] = mythread.MyThread( self.SendMessageThread, Name="SendMessageThread") except Exception as e1: self.LogErrorLine("Error opening serial device in MyModem: " + str(e1))