def start(self, logger=False, doc_path='/docs', show_doc=True, block=False, function=False): def handler(callback): callback() if (block): self.__blocking_loop() if (network.WLAN(network.STA_IF).isconnected() or network.WLAN(network.AP_IF).active()): self.logger.active = logger if (show_doc): self.__docs.start(doc_path) self.__start_listening() threading.start_new_thread(self.__handle_server, ()) if (function): return handler if (block): self.__blocking_loop() else: raise Exception('Wifi is not setup correctly.')
def __init__(self, parent, id, title, size): '初始化,添加控件并绑定事件' wx.Frame.__init__(self, parent, id, title) self.SetSize(size) self.Center() self.chatFrame = wx.TextCtrl(self, pos=(5, 5), size=(490, 310), style=wx.TE_MULTILINE | wx.TE_READONLY) self.message = wx.TextCtrl(self, pos=(5, 320), size=(300, 25)) self.sendButton = wx.Button(self, label="Send", pos=(310, 320), size=(58, 25)) self.usersButton = wx.Button(self, label="Users", pos=(373, 320), size=(58, 25)) self.closeButton = wx.Button(self, label="Close", pos=(436, 320), size=(58, 25)) self.sendButton.Bind(wx.EVT_BUTTON, self.send) self.usersButton.Bind(wx.EVT_BUTTON, self.lookUsers) self.closeButton.Bind(wx.EVT_BUTTON, self.close) threading.start_new_thread(self.receive, ()) self.Show()
def network_test(first=None): type = GC.LINK_PROFILE stop_server = None #通过域名解析测试网络状态 if not is_active(type): #对应网络全部发生故障时才停止代理线程 fail_type = 'ipv' if '4' in type and not internet_v4.last_stat: fail_type += '4' if '6' in type and not internet_v6.last_stat: fail_type += '6' if type == fail_type: stop_server = True if stop_server: if not first: stop_proxyserver() is_active(fail_type, 10) else: start_new_thread(is_active, (fail_type, 10)) if stop_server or first: get_localhosts() #重新开始代理线程 if stop_server: if first: note = '初始化继续' else: note = '重新开始代理' start_proxyserver() logging.warning('网络已经可以使用,%s……', note)
def mdHandler(size): try: #Needs to have 2 threads for multithreading to check multiprocessing threading.start_new_thread(mdtest, size) threading.start_new_thread(mdtest, size) except: print("Working")
def main(port=4118, parentpid=None): """Main entry point. Parse command line options and start up a server.""" if os.environ.has_key("LDTP_DEBUG"): _ldtp_debug = True else: _ldtp_debug = False _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None) server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug, requestHandler=RequestHandler) server.register_introspection_functions() server.register_multicall_functions() ldtp_inst = core.Core() server.register_instance(ldtp_inst) if parentpid: thread.start_new_thread(notifyclient, (parentpid, )) try: server.serve_forever() except KeyboardInterrupt: pass except: if _ldtp_debug: print(traceback.format_exc()) if _ldtp_debug_file: with open(_ldtp_debug_file, "a") as fp: fp.write(traceback.format_exc())
def thread_new(): try: threading.start_new_thread(print_test, ('TA', )) threading.start_new_thread(print_test, ('TB', )) except: print(1) pass
def open_fifo_write(path, data): '''open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process (such as ssh-agent) reads data from the pipe. ''' os.mkfifo(path, 0o600) threading.start_new_thread(lambda p, d: open(p, 'w').write(d), (path, data))
def do_stuff(): a_list = [] threading.start_new_thread(input_thread, (a_list, )) while not a_list: x = 0 while x >= 0: print(x) x += 1
def listenClients(self): while 1: clientsoc, clientaddr = self.serverSoc.accept() self.setStatus("Client connected from %s:%s" % clientaddr) self.addClient(clientsoc, clientaddr) threading.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr)) self.serverSoc.close()
def start(self): if self.running: return if self.enable: self.running = True if not hasattr(self.ip_source, 'get_cnt'): self.ip_source.check_update(force=True) start_new_thread(self.recheck_ip_worker, ())
def spawn_later(seconds, target, *args, **kwargs): def wrap(*args, **kwargs): sleep(seconds) try: target(*args, **kwargs) except Exception as e: logging.warning('%s.%s 错误:%s', target.__module__, target.__name__, e) start_new_thread(wrap, args, kwargs)
def do_POST(self): if self.path.startswith('/kill_server'): print("Server is going down, run it again manually!") def kill_me_please(server): server.shutdown() threading.start_new_thread(kill_me_please, (httpd, )) self.send_error(500)
def check_pick_ip_worker(self): new_worker_cnt = min((self.max_cnt - len(self.ip_list)) * 2, self.max_threads or 1) - self.pick_worker_cnt if new_worker_cnt > 0: self.pick_worker_cnt += new_worker_cnt for _ in range(new_worker_cnt): start_new_thread(self.pick_ip_worker, ()) sleep(0.5) elif new_worker_cnt < 0: self.kill_pick_worker_cnt = - new_worker_cnt
def main(setup, error): file = open(error, 'a') # open file for error messages sys.stderr = file.write(error) # read settings for port forwarding for settings in parse(setup): thread.start_new_thread(server, settings) # wait for <ctrl-c> while True: time.sleep(60)
def __init__(self, max_items, expire=0): # expire == 0:最近最少使用过期 # expire > 0:最近最少使用过期 + 时间过期 self.cache = {} self.key_order = collections.deque() self.max_items = int(max_items) self.expire = int(expire) self.lock = threading.Lock() if self.expire > 0: start_new_thread(self._cleanup, ())
def __init__(self, max_items, expire=None): self.cache = {} self.max_items = int(max_items) self.expire = expire self.key_expire = {} self.key_noexpire = set() self.key_order = collections.deque() self.lock = threading.Lock() if expire: start_new_thread(self._cleanup, ())
def create_ssl_connection(self, address, hostname, cache_key, getfast=None, forward=None, **kwargs): def get_cache_sock(): try: while cache: ctime, ssl_sock = cache.pop() if self.check_connection_alive(ssl_sock._sock, self.keeptime, ctime): return ssl_sock except IndexError: pass cache = self.ssl_connection_cache[cache_key] sock = get_cache_sock() if sock: return sock result = None host, port = address addresses = [(x, port) for x in dns[hostname]] for i in range(self.max_retry): addresseslen = len(addresses) if getfast and gae_testgwsiplist: #按线程数量获取排序靠前的 IP addresses.sort(key=self.get_ssl_connection_time) addrs = addresses[:autorange_threads + 1] else: if addresseslen > self.max_window: addresses.sort(key=self.get_ssl_connection_time) window = min((self.max_window + 1)//2 + min(i, 1), addresseslen) addrs = addresses[:window] + random.sample(addresses[window:], self.max_window-window) else: addrs = addresses queobj = Queue() for addr in addrs: start_new_thread(self._create_ssl_connection, (addr, cache_key, host, queobj, forward, get_cache_sock)) addrslen = len(addrs) for n in range(addrslen): result = queobj.get() if isinstance(result, Exception): addr = result.xip if addresseslen > 1: #临时移除 badip try: addresses.remove(addr) addresseslen -= 1 except ValueError: pass if i == n == 0 and not isinstance(result, LimiterFull): #only output first error logging.warning('%s _create_ssl_connection %r 返回 %r,重试', addr[0], host, result) else: if addrslen - n > 1: start_new_thread(self._close_ssl_connection, (cache, addrslen-n-1, queobj, result.ssl_time)) return result if result: raise result
def __del__(self): if self._key: self._key, key = None, self._key try: limiter = self.limiters[key] except KeyError: pass else: limiter.pop(block=False) start_new_thread(self.clearup, (key, )) return True
def start_proxyserver(): reset_dns() try: AutoProxy.bind_and_activate() GAEProxy.bind_and_activate() start_new_thread(AutoProxy.serve_forever, ()) start_new_thread(GAEProxy.serve_forever, ()) except SystemError as e: if '(libev) select: Unknown error' in repr(e): wait_exit('如果出现此错误请告诉作者,谢谢!\nhttps://github.com/SeaHOH/GotoX/issues', exc_info=True) AutoProxyHandler.bufsize = AutoProxy.socket.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
def run_with_reloader(runner): if os.environ.get('RUN_FLAG') == 'true': threading.start_new_thread(runner, ()) try: start_change_detector() except KeyboardInterrupt: pass else: try: sys.exit(restart_with_reloader()) except KeyboardInterrupt: pass
def resolve_iplist(): def do_resolve(host, queobj): try: iplist = dns_resolve(host) queobj.put((host, iplist)) except OSError as e: logging.error('自定义 IP 列表解析失败:host=%r,%r', host, e) queobj.put((host, None)) # https://support.google.com/websearch/answer/186669?hl=zh-Hans # forcesafesearch.google.com google_blacklist = ['216.239.38.120', '2001:4860:4802:32::78'] for name, need_resolve_hosts in list(GC.IPLIST_MAP.items()): if name in ('google_gae', 'google_gws'): continue resolved_iplist = [x for x in need_resolve_hosts if isip(x)] need_resolve_hosts = [ x for x in need_resolve_hosts if '.' in x and x not in resolved_iplist ] if not need_resolve_hosts: continue if GC.LINK_PROFILE == 'ipv4': resolved_iplist = [ ip for ip in resolved_iplist if isipv4(ip) ] elif GC.LINK_PROFILE == 'ipv6': resolved_iplist = [ ip for ip in resolved_iplist if isipv6(ip) ] result_queue = queue.Queue() for host in need_resolve_hosts: logging.debug('自定义 IP 列表解析开始:host=%r', host) start_new_thread(do_resolve, (host, result_queue)) for _ in need_resolve_hosts: host, iplist = result_queue.get() if iplist: resolved_iplist += iplist logging.debug('自定义 IP 列表解析成功:host=%r,iplist=%s', host, iplist) if name.startswith('google_'): resolved_iplist = list( set(resolved_iplist) - set(google_blacklist)) else: resolved_iplist = list(set(resolved_iplist)) if len(resolved_iplist) == 0: logging.warning('自定义 IP 列表 %r 解析结果为空,请检查你的配置 %r。', name, GC.CONFIG_FILENAME) else: logging.info('IP 列表 %r 解析结果:iplist=%r', name, resolved_iplist) GC.IPLIST_MAP[name] = resolved_iplist
def _dns_over_https_resolve(qname, qtypes=qtypes): iplist = classlist() xips = [] queobj = queue.Queue() for qtype in qtypes: start_new_thread(_https_resolve, (qname, qtype, queobj)) for qtype in qtypes: _iplist, xip = queobj.get() iplist += _iplist if xip and xip not in xips: xips.append(xip) if xips: iplist.xip = '|'.join(xips), return iplist
def init_server(self): """ Initialize and start the server thread, if not already initialized. """ if self.server is not None: return if rosgraph.network.use_ipv6(): s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((rosgraph.network.get_bind_address(), self.port)) if self.port == 0: self.port = s.getsockname()[1] self.server = s threading.start_new_thread(self.run, ())
def handleAddClient(self): if self.serverStatus == 0: self.setStatus("Set server address first") return clientaddr = (self.clientIPVar.get().replace(' ', ''), int(self.clientPortVar.get().replace(' ', ''))) try: clientsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsoc.connect(clientaddr) self.setStatus("Connected to client on %s:%s" % clientaddr) self.addClient(clientsoc, clientaddr) threading.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr)) except: self.setStatus("Error connecting to client")
def login(request): try: threading.start_new_thread(autoupdate, (5, )) except: print("Error: unable to start thread") if request.method == 'POST': login_info = user_login(request.POST) result = {'user_pass': False, 'captcha': False, 'isadmin': False} if login_info.is_valid(): if verify_user_info(str(login_info.cleaned_data['user_id']), str(login_info.cleaned_data['user_password'])): result['user_pass'] = True result['captcha'] = True request.session['user_id'] = str( login_info.cleaned_data['user_id']) # 创建session # 判断用户权限 if isadmin_user_info(request.session.get('user_id')): result['admin'] = True # 返回JSON格式的对象 return HttpResponse(simplejson.dumps(result, ensure_ascii=False), content_type="application/json") # return HttpResponseRedirect('/backend/index/') else: # 返回JSON格式的对象 return HttpResponse(simplejson.dumps(result, ensure_ascii=False), content_type="application/json") # return HttpResponseRedirect('/front/index/') else: result['captcha'] = True # 返回JSON格式的对象 return HttpResponse(simplejson.dumps(result, ensure_ascii=False), content_type="application/json") else: print(login_info.cleaned_data) print("验证码错误!") return HttpResponse(simplejson.dumps(result, ensure_ascii=False), content_type="application/json") else: hashkey = CaptchaStore.generate_key() imgage_url = captcha_image_url(hashkey) tp = loader.get_template("login.html") html = tp.render({"hashkey": hashkey, "imgage_url": imgage_url}) return HttpResponse(html)
def run(self): def f(): mesIgnor = set([]) termLim = self.termLim while termLim > 0: mes = self.client.getMes() if mes and mes not in mesIgnor: mesIgnor.add(mes) res = self.respond(mes) if not res: break else: self.client.send(mes) time.sleep(wait) termLim -= 1 threading.start_new_thread(f)
def Start(self): self.enable = True page = self.page print(u'正在加载中请稍候......') # 新建一个线程在后台加载段子并存储 threading.start_new_thread(self.LoadPage, ()) # ----------- 加载处理糗事百科 ----------- while self.enable: # 如果self的page数组中存有元素 if self.pages: nowPage = self.pages[0] del self.pages[0] self.ShowPage(nowPage, page) page += 1
def on_open(ws): # 线程运行函数 def gao(): # 往服务器发送0-4,每次发送完休息0.1秒 for i in range(5): time.sleep(0.1) msg = "{0}".format(i) ws.send(msg) print("发送了:" + msg) # 休息1秒用于接受服务器回复的消息 time.sleep(1) # 关闭websocket连接 ws.close() print("websocket关闭了") # 在另一个线程运行gao函数 threading.start_new_thread(gao, ())
def on_open(ws): # 线程运行函数 def gao(): # 往服务器依次发送0-4,每次发送完休息0.01秒 for i in range(5): time.sleep(0.01) msg = "{0}".format(i) ws.send(msg) print('Sent: ' + msg) # 休息1秒用于接收服务器回复的消息 time.sleep(1) # 关闭Websocket的连接 ws.close() print("Websocket closed") # 在另一个线程运行gao()函数 thread.start_new_thread(gao, ())
def handleSetServer(self): if self.serverSoc != None: self.serverSoc.close() self.serverSoc = None self.serverStatus = 0 serveraddr = (self.serverIPVar.get().replace(' ', ''), int(self.serverPortVar.get().replace(' ', ''))) try: self.serverSoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSoc.bind(serveraddr) self.serverSoc.listen(5) self.setStatus("Server listening on %s:%s" % serveraddr) threading.start_new_thread(self.listenClients, ()) self.serverStatus = 1 self.name = self.nameVar.get().replace(' ', '') if self.name == '': self.name = "%s:%s" % serveraddr except: self.setStatus("Error setting up server")
def main(): arr = [] t = threading.start_new_thread( mythread, (arr,) ) ticks = 0 while len(arr) < 100: ticks += 1 if ticks > 100000: ## do not hangup if there is a bug in the webworker break TestError( sum(arr) == 4950 )
def main(): c = [] t = threading.start_new_thread( mythread, ('hello', 'worker', c) ) sleep(0.1) ticks = 0 while len(c) < 2: ticks += 1 if ticks > 100000: ## do not hangup if there is a bug in the webworker break TestError( c[0] == 'hello' ) TestError( c[1] == 'worker' )
def main(): shared1 = {} shared2 = {'z':100} t = threading.start_new_thread( mythread, (shared1, shared2, BACKEND=='JAVASCRIPT') ) ticks = 0 while len(shared1) + len(shared2) < 2: ticks += 1 if ticks > 10000: ## do not hangup if there is a bug in the webworker break TestError( shared1['x'] == 'hello' ) TestError( shared2['y'] == 'world' ) TestError( shared2['z'] == 100 )
def main(): shared1 = [] shared2 = [] t = threading.start_new_thread( mythread, (shared1, shared2) ) ticks = 0 while len(shared1) + len(shared2) < 4: ticks += 1 if ticks > 100000: ## do not hangup if there is a bug in the webworker break shared1.append( 'ZZZ' ) TestError( shared1[0] == 'hello' ) TestError( shared2[0] == 'world' ) TestError( shared2[1] == 'YYY' ) ticks = 0 while ticks < 100000: ticks += 1
__author__ = 'hzliyong' import threading import time def print_time(threadName,delay): count = 0; while count < 5: time.sleep(delay) count += 1 print("%s:%s"%(threadName,time.ctime(time.time()))) try: threading.start_new_thread(print_time,("Thread-1",2)) threading.start_new_thread(print_time,("Thread-2",4)) except: print("Error:unable to start thread") while 1: pass
try: if action == 'stop': win32serviceutil.StopService(DATADOG_SERVICE) elif action == 'start': win32serviceutil.StartService(DATADOG_SERVICE) elif action == 'restart': win32serviceutil.RestartService(DATADOG_SERVICE) except Exception as e: warning_popup("Couldn't %s service: \n %s" % (action, str(e))) def service_manager(action, async=True): if not async: _service_manager(action) else: thread.start_new_thread(_service_manager, (action,)) def get_service_status(): try: return win32serviceutil.QueryServiceStatus(DATADOG_SERVICE)[1] except Exception: return "Unknown" def is_service_running(status=None): if status is None: status = get_service_status() return status == win32service.SERVICE_RUNNING