def run(self): self._sock.listen(5) while True: conn, addr = self._sock.accept() print("Connected with " + addr[0] + ":" + str(addr[1])) _start_new_thread(self.diffieHellmanThread, (conn,))
def start_thread(self, lock=None): assert lock or self.lock if lock: self.lock = lock if self.ready: threading._start_new_thread( self.loop, () ) else: print('Warning: no webcam found')
def __init__(self): self.closed = False self.objects = {} self.scale = 3 master = Tk() master.title("B0rbit - The ultimate DarkOrbit b0t. Beta v0.1") master.protocol("WM_DELETE_WINDOW", self._winExitHandler) self.w = Canvas(master, width=200 * self.scale, height=125 * self.scale) self.w.pack() self.w.create_rectangle(0, 0, 200 * self.scale, 125 * self.scale, fill="black") self._lineHeroY = self.w.create_line(0 * self.scale, 55 * self.scale, 200 * self.scale, 55 * self.scale, fill="blue") self._lineHeroX = self.w.create_line(100 * self.scale, 0 * self.scale, 100 * self.scale, 125 * self.scale, fill="blue") self._textInfoBox = self.w.create_text(10, 10, anchor=NW, text="Lade...", fill="white") threading._start_new_thread(mainloop, ())
def start_threads( self, lock ): if self.kinect.ready: threading._start_new_thread( self.kinect.loop, (lock,) ) threading._start_new_thread( self.proc_contours.loop, (lock,) ) #threading._start_new_thread( self.proc_shapes.loop, (lock,) ) else: print( 'Warning: no kinect devices found' )
def login_danmu_server(self, is_all_danmu = False): if self.__gid == None: if not self.login_danmu_auth_server(): print('Login danmu auth server failed') return False login_info = self.__douyu_login_client.get_login_info() self.__recv_danmu_socket.connect(danmu_client.__address_danmu_1) login_data = 'type@=loginreq/username@=' + login_info['acf_username'] + '/password@=1234567890123456/roomid@=' + self.__room_id self.__send_msg(login_data, self.__recv_danmu_socket) recv_data = self.__get_next_data(self.__recv_danmu_socket) parse_result = self.__parse_recv_msg(recv_data) if 'type' in parse_result and parse_result['type'] == 'loginres': if is_all_danmu: join_group = 'type@=joingroup/rid@=' + self.__room_id + '/gid@=' + '-9999' else: join_group = 'type@=joingroup/rid@=' + self.__room_id + '/gid@=' + self.__gid self.__send_msg(join_group, self.__recv_danmu_socket) threading._start_new_thread(self.__recv_socket_keep_alive, ())
def __init__(self, address, listenerport): self.listener, self.listenerAddress = None, None self.listenerBase = socket.socket() self.listenerBase.bind((address, listenerport)) self.listenerBase.listen(1) self.sender = socket.socket() threading._start_new_thread(self.THREAD_connectionscatcher, ())
def main(): print('knock knock') a = input('') print('Interrupting cow.') threading._start_new_thread(interrupt, (3,)) b = input('')
def jdpay_wap(): env_name, root_url, live_key, app_id = datagen.get_current_env() url = "{0}/v1/charges".format(root_url) # request body charge = Model.ChargeBase.ChargeDict charge['order_no'] = random_str(10) charge['subject'] = 'TestOrder4jdpay_wap' charge['body'] = 'appletest4Pay' charge['amount'] = 10 charge['channel'] = 'jdpay_wap' charge['currency'] = 'cny' charge['client_ip'] = '127.0.0.1' id = [('id', app_id)] extra = [("success_url", "http://pingxx.com"), ("fail_url", "htpps://pingxx.com")] charge['app'] = dict(id) charge['extra'] = dict(extra) mycharge = APIClient._http_call(url, "post", "json", "json", None, {"Authorization": "Bearer {0}".format(live_key)}, 30, **charge) print(mycharge) sshCmd.ssh_cmd("114.215.237.77", "56f27c2B", "echo "">/var/www/example/ziteng") threading._start_new_thread(sshCmd.ssh_cmd("114.215.237.77", "56f27c2B", "echo "">/var/www/example/ziteng")) time.sleep(5) Forward.forward_json(mycharge) ret = sshCmd.ssh_cmd("114.215.237.77", "56f27c2B", "echo "">/var/www/example/ziteng") print ret if int(filter(lambda x: x.isdigit(), ret)) > 1: print "The charge file had updated on %s" % ctime() else: print "forward the charge to update file again..." threading._start_new_thread(sshCmd.ssh_cmd("114.215.237.77", "56f27c2B", "echo "">/var/www/example/ziteng")) time.sleep(2) Forward.forward_json(mycharge)
def card_shuffle(): global card random.shuffle(card) set_filename("card_shuffle") threading._start_new_thread(play_sound,()) print ("\n카드를 섞는 중입니다...\n") print ("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n")
def tell_story(count): time.sleep(5) print(story[count]) if not count + 1 == len(story): threading._start_new_thread(tell_story, (count + 1,))
def start(self): self.active = True self.loops = 0 if hasattr(self,'setup'): self.setup() if threading: threading._start_new_thread( self.loop, () ) else: thread.start_new_thread( self.loop, () )
def connect(): print("connect()") global s, conn, CONN_Flag while 1: conn, addr=s.accept() CONN_Flag=True threading._start_new_thread(recv_msg,()) print("connect success :", addr)
def connect(self, address, listenerport): # self.connectionsCatcher.terminate() self.sender.connect((address, listenerport)) # I sender connects to II listener self.connecting = True self.sender.send(str(self.listenerBase.getsockname()[1]).encode()) # I sender sends I listener's port to IIs # look at ConnectionsCatcher # I listener accepts connection from II sender theirAddress, theirPort = address, listenerport threading._start_new_thread(self.THREAD_listener, ())
def __init__(self, parent, mylist, header, *args): QAbstractTableModel.__init__(self, parent, *args) self.mylist = mylist self.header = header self.count = 0 self.timer = QTimer() #self.timer.setInterval(1) self.timer.start(1000) self.timer.timeout.connect(self.timerHit) threading._start_new_thread(self.updateData, ())
def _send_when_ready(self, message): self.socket.pendingRequests += 1 try: self.socket.send(message.encode()) except websocket.WebSocketException as e: # Socket isn't open. open it. Attempt to open it only once print("Caching message: " + message) if not self.socket.attempting: threading._start_new_thread(self.socket.run_forever, ()) self.socket.attempting = True self.socket.messageCache.append(message)
def _start_ticking(self): if debug > 4: print 'start ticking' self.semaphore = Semaphore(0) self._scheduler = scheduler scheduler.seconds_from_now_do(1.0, self._tick) # @fixme Switching to Thread object caused # mpx/lib/bacnet/_test_case_bvlc.py to hang after completing. # Figure out why, and switch over the Thread object. threading._start_new_thread(self._tock,())
def THREAD_connectionscatcher(self): self.listener, self.listenerAddress = self.listenerBase.accept() # II listener accepts connection of I sender if self.connecting: return 0 print(self.listenerAddress[0]) data = self.listener.recv(2048) print(int(data.decode())) self.sender.connect((self.listenerAddress[0], int(data.decode()))) # II sender connects to I listener print(self.sender.getsockname()) threading._start_new_thread(self.THREAD_listener, ())
def alarm(secs): def wait(secs): for n in xrange(timeout_secs): time.sleep(1) if signal_finished: break else: #thread.interrupt_main() exec_errors.append(SafeEvalTimeoutException(secs).message) #thread.Start_new_thread(wait, (secs,)) threading._start_new_thread(wait, (secs,))
def onclick_hand(event): global card, tmp_throw_card if(my_turn==True): for i in range(len(card)): if(event.widget==cardLabels[i]): print("clickcard") zoom_image(2) tmp_throw_card=card[i] get_throw_cardImg(tmp_throw_card) get_value() threading._start_new_thread(get_decide, ())
def __init__(self, interpreter): super().__init__(interpreter) self.__pymouse = pymouse.PyMouse() self.__mouse_click_event = MouseClickEvent(self) self._left_down = False self._right_down = False # noinspection PyProtectedMember threading._start_new_thread(self.__mouse_click_event.run, tuple())
def _listener(self): while self._alive: rd, wr, err = select.select([self._server], [], []) for s in rd: if s is self._server: client_skt, client_addr = self._server.accept() self._lock.acquire() self._clients.append(client_skt) self._lock.release() threading._start_new_thread(self._handle_client, (client_skt, client_addr)) self._server.close() print("Server closed")
def makeServer(): s = socket(AF_INET, SOCK_STREAM) s.bind(Addr) s.listen(5) while True: print("waiting for connection....") tcpClient, addr = s.accept() tcpClient.send("Connected".encode()) print("connected from ", addr) threading._start_new_thread(ConnectedClient, (tcpClient, addr))
def __init__(self, filename, aut=False): self.filename = filename self.aut = aut if filename[-2:] == "gr": self.single = True else: self.single = False self.g = loadgraph(filename, readlist=not self.single) if not self.single: self.g = self.g[0] print("Launching job [%s]..."%filename) threading._start_new_thread(self.run, tuple())
def process_match(self, data): """Calculate the closest match and add it to the data """ def worker(q, data): """Spawns signature worker. """ thread = lib.signature.Worker(self.logger, self.flags, self.signatures, self.coordinates, data) thread.start() q.put(thread, True) def getter(q, num): """Gets the result from the workers. """ data = {} for i in range(num): thread = q.get(True) thread.join() # Grab the result result = thread.get_result() if not (self.flags['break'] and self.flags['break_value'] == 'matching'): self.logger.info("Progress signature: {0}/{1}".format(i+1, num)) data.update(result) return data threads = int(multiprocessing.cpu_count()) q = queue.Queue(threads) length = len(data) step = math.ceil(length/threads) if step == 0: step = 1 num = 0 for num,i in enumerate(range(0,length,step)): data_part = {} if i+step <= length: keys = list(data.keys()) keys = keys[i:i+step] else: keys = list(data.keys()) keys = keys[i:length] for key in keys: data_part[key] = data[key] threading._start_new_thread(worker, ((q, data_part))) data = getter(q,num+1) return data
def connect(self, ip='192.168.0.200', port=5550): """Connect with the command station Args: ip: Command station ip port: Command station port. Returns: None """ self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((ip,port)) data = "f101" self.send_data(data) self.command_station_status_request() # this sets the self.mushroom to the init value threading._start_new_thread(self.handle_recieved, (False,))
def start(): class RequestHandler(SocketServer.BaseRequestHandler): def handle(self): global status self.data = self.request.recv(1024).strip() if self.data == "00": status = 1 server = SocketServer.TCPServer(("192.168.1.3",9001), RequestHandler) threading._start_new_thread(server.serve_forever,()) return 0
def deferToThread(self, callback, func, *args, **kw): """ Defer a function to a thread and callback the return value. @type callback: function @param callback: function to call on completion @type cbargs: tuple or list @param cbargs: arguments to get supplied to the callback @type func: function @param func: function to call """ def f(func, callback, *args, **kw): ret = func(*args, **kw) self.setTimeout(0, callback, ret) threading._start_new_thread(f, (func, callback) + args, kw)
def listenToiOS(self): """Listen to incoming message""" self.listenSocket =socket.socket(socket.AF_INET,socket.SOCK_STREAM) #self.listenSocket.bind((self.localIP,self.localPort)) self.listenSocket.bind(("",17642)) self.listenSocket.listen(5) print "Listening from iOS..." #(clientsocket, address) = threading.Thread(target=self.listenSocket.accept).start() threading._start_new_thread(self.listenSocket.accept,self) #self.playEvent = threading.Event() #self.playEvent.clear() #(clientsocket, address) = self.listenSocket.accept() print "Connection Accepted..."
def main2(): pase_param() init_log() init_code() load_mime() auth.disable() server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: server_sock.bind((config["bind_ip"],config["bind_port"])) server_sock.listen(5) while True: accept = server_sock.accept() threading._start_new_thread(http_proc,(accept[0],accept[1])) except Exception ,e: print (e,config)
def schedule_run(self, app): """ Tries to run an application. The algorithm is to get all input apps into the FINISHED state (by calling schedule_run for them if needed) and calling prepare() and run() for the actual app. :param app: :return: """ # debug("schedule run for "+str(app)) if app in self.__run_stack: # debug("stack contains "+str(app)) return self.__run_stack.append(app) # app.connect("statusChanged", self.__process_run_signals(app)) app.status_changed.connect(self.__process_run_signals(app)) _start_new_thread(self.__schedule_run, (app,))
def _listener_thread_loop(self): self.active = True while self.active: ready = select.select([self.listen_socket], [], [], 1000)[0] if ready: #self.lock.acquire() for sock in ready: print('main listener', sock) startsock, address = sock.accept() #self.top_new_client(startsock, address) # sets.client and calls new_client() threading._start_new_thread(self.top_new_client, (startsock, address)) print('main listener topped') #self.lock.release() print('listening...')
def attend_new_nodes(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((self.node.ip, 8081)) while True: msg = None try: msg, _ = sock.recvfrom(1024) except Exception as ex: print('EXCEPCION EN attend_new_nodes') print(ex) continue if msg is not None: data = json.loads(msg) addr = data['sender'][1], data['sender'][2] threading._start_new_thread(self.proccess_message, (data, addr, True))
def create_server(ADDR): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(ADDR) sock.listen(10) while True: print("waiting for connection") tcpClientSocket,addr = sock.accept() print("connect from",addr) threading._start_new_thread(rec_process,(tcpClientSocket,)) threading._start_new_thread(send_buf,(tcpClientSocket,)) tcpClientSocket.close() sock.close()
def accepting_to_server(self): while True: self.server_socket.listen(7) self.conn, self.adress = self.server_socket.accept() self.new_thread = threading._start_new_thread( on_new_client, (self.conn, self.adress)) self.threads.append(self.new_thread)
def __init__(self): self._scene_loaded = False self._objects = {} self._materials = {} self.buffer = [] # cmd buffer self.callbacks = [ self.update_view, self.update_selected, self.update_materials ] ## launch Tundra ## if sys.platform == 'linux2': exe = os.path.join( CONFIG_TUNDRA, 'run-server.sh' ) assert os.path.isfile( exe ) cmd = [exe, '--config', TUNDRA_CONFIG_XML_PATH, '--fpslimit', '100', '--storage', '/tmp/'] print( cmd ) p = subprocess.Popen(cmd, stdin=subprocess.PIPE) else: exe = os.path.join( CONFIG_TUNDRA, 'Tundra.exe' ) assert os.path.isfile( exe ) cmd = [exe, '--file', PREVIEW, '--config', TUNDRA_CONFIG_XML_PATH] p = subprocess.Popen(cmd, stdin=subprocess.PIPE) self.proc = p self.socket = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host='localhost'; port = 9978 sock.connect((host, port)) print('socket connected', sock) self._handle = None self.setup_callback( bpy.context ) self.ready = threading._allocate_lock() self.ID = threading._start_new_thread( self.loop, (None,) ) print( '.....thread started......')
def start_server(): global server, HOST_ADDR, HOST_PORT # code is fine without this btnStart.config(state=tk.DISABLED) btnStop.config(state=tk.NORMAL) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(socket.AF_INET) print(socket.SOCK_STREAM) server.bind((HOST_ADDR, HOST_PORT)) server.listen(5) # server is listening for client connection threading._start_new_thread(accept_clients, (server, " ")) lblHost["text"] = "Host: " + HOST_ADDR lblPort["text"] = "Port: " + str(HOST_PORT)
def run_http(): global httpd if httpd: print("WARN: httpd is already running") return try: httpd = SocketServer.TCPServer(("", 8081), Handler) except OSError: ## [Errno 98] Address already in use httpd = None if httpd: threading._start_new_thread( httpd.serve_forever, tuple([]) ) print('running http on localhost:8081') else: print('ERROR: failed to run http on localhost:8081') sys.exit(1)
def get_cordinate(xy): global client, your_turn, you_started label_index = xy[0] * num_cols + xy[1] label = list_labels[label_index] if your_turn: if label["ticked"] is False: label["label"].config(foreground=your_details["color"]) label["label"]["text"] = your_details["symbol"] label["ticked"] = True label["symbol"] = your_details["symbol"] client.send("$xy$" + str(xy[0]) + "$" + str(xy[1])) your_turn = False # Does this play leads to a win or a draw result = game_logic() if result[0] is True: if you_started: message = opponent_details[ "symbol"] + " empieza la proxima ronda" else: message = your_details[ "symbol"] + " empieza la proxima ronda" if result[0] is True and result[1] != "": your_details["score"] = your_details["score"] + 1 tkMessageBox.showinfo( title="Ganaste!", message="Player " + your_details["symbol"] + ": " + str(your_details["score"]) + " Player " + opponent_details["symbol"] + ": " + str(opponent_details["score"]) + '\n\n' + message) threading._start_new_thread(init, ("", "")) elif result[0] is True and result[1] == "": tkMessageBox.showinfo( title="Empate", message="Player " + your_details["symbol"] + ": " + str(your_details["score"]) + " Player " + opponent_details["symbol"] + ": " + str(opponent_details["score"]) + '\n\n' + message) threading._start_new_thread(init, ("", "")) elif opponent_details['name'] == "": tkMessageBox.showinfo(title="Error", message="Esperando por el jugador 2") else: tkMessageBox.showinfo(title="Error", message="No es tu turno")
def __init__(self): QtWidgets.QWidget.__init__(self) data_layout = QtWidgets.QHBoxLayout() self.refresh_text.connect(self.refresh_data) self.connections = [] self.channels = QtWidgets.QListWidget() self.channels.setFocusPolicy(QtCore.Qt.NoFocus) self.channels.setDragEnabled(False) self.channels.setFixedWidth(200) self.users_list = QtWidgets.QListWidget() self.users_list.setFocusPolicy(QtCore.Qt.NoFocus) self.users_list.setFixedWidth(150) if isfile("./settings"): self.load_settings() font = QtGui.QFont("Comic Sans") font.setPointSize(8) self.channels.setFont(font) self.irc_text_data = QtWidgets.QTextEdit() self.irc_text_data.setFocusPolicy(QtCore.Qt.NoFocus) self.irc_text_data.setReadOnly(True) data_layout.addWidget(self.channels) data_layout.addWidget(self.irc_text_data) data_layout.addWidget(self.users_list) self.send_message_line = QtWidgets.QLineEdit() self.send_message_line.setFocusPolicy(QtCore.Qt.StrongFocus) self.send_message_line.setPlaceholderText("Send Message") main_layout = QtWidgets.QVBoxLayout() main_layout.addLayout(data_layout) main_layout.addWidget(self.send_message_line) self.setLayout(main_layout) self.send_message_line.returnPressed.connect(self.send_message) self.channels.clicked.connect(self.refresh_data) threading._start_new_thread(self.hold_connections, ()) atexit.register(self.save_settings)
def init_thread(): #threading._start_new_thread(base.main_task,()) #threading._start_new_thread(base.handle_main_task,()) #threading._start_new_thread(base.beat_main_task,()) #threading._start_new_thread(base.task_main_task,()) threading._start_new_thread(main_task, ()) threading._start_new_thread(handle_main_task, ()) threading._start_new_thread(beat_main_task, ()) threading._start_new_thread(task_main_task, ())
def run(self): self.runFlag = True for leads in range(self.numofleads): self.current_lead = leads if self.son_type == "Water": #Start the water ambience sonification threading._start_new_thread(SONM.st_sonification_wa, (self.current_lead, self.ecgpeaks[leads],self.st_amp_lead[leads],self.st_amp_all_data[leads],self.numofleads,self.pl_stretch_water,self.wind_state, self.thund_state, self.rain_state, self.mainWindow)) elif self.son_type == "Morph": #start the morph sonification threading._start_new_thread(SONM.st_sonification_mo, (self.current_lead, self.ecgpeaks[leads], self.st_amp_lead[leads], self.st_amp_all_data[leads], self.numofleads, self.pl_stretch_morph,self.RpeakUpFr, self.TwaveUpFr, self.total_pln_cnt, self.SoundEventsDur, self.mainWindow))
def On(self): self.Enable.config(state=tk.DISABLED) self.Disable.config(state=tk.NORMAL) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("attempt to bind server") server.bind((self.HOST_ADDR, self.HOST_PORT)) print("attempt to listen for clients") server.listen(5) # server is listening for client connection print("starting new thread") threading._start_new_thread(self.join, (server, " ")) self.Host["text"] = "Host IP: " + self.HOST_ADDR self.Port["text"] = "Port: " + str(self.HOST_PORT) print("successfully up")
def connect_to_server(name): global client, HOST_ADDR, HOST_PORT client = None HOST_ADDR = "127.0.0.1" HOST_PORT = 6537 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST_ADDR, HOST_PORT)) client.send(bytes(name, "utf8")) entName.config(state=tkinter.DISABLED) btnConnect.config(state=tkinter.DISABLED) tkMessage.config(state=tkinter.NORMAL) threading._start_new_thread(receive_message_from_server, (client, "m"))
def test(): def test_proc(i, l): while True: val = l.pop() if type(val) is int: print "i am " + str(i) + " receive " + str(val) + "\n" elif type(val) is bool: print "i am " + str(i) + " bye.\n" return l = SafeList(0) for i in range(0, 10): threading._start_new_thread(test_proc, (i, l)) for i in range(0, 10): l.push(i) for i in range(0, 10): l.push(False)
def stat_serv(): global server, HST_ADR, HST_PRT btSt.config(state=tk.DISABLED) btStp.config(state=tk.NORMAL) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print (socket.AF_INET) print (socket.SOCK_STREAM) server.bind((HST_ADR, HST_PRT)) server.listen(5) # server is listening for client connection threading._start_new_thread(accept_clients, (server, " ")) lablHost["text"] = "Address: " + HST_ADR lablPort["text"] = "Port: " + str(HST_PRT)
def __init__(self, playerData, networkingObj): self.name = playerData["name"] self.userID = playerData["userID"] self.x = float(playerData["x"]) self.y = float(playerData["y"]) self.speed = float(playerData["speed"]) self.credits = int(playerData["credits"]) self.uridium = int(playerData["uridium"]) self.hp = int(playerData["hp"]) self.hpmax = int(playerData["hpmax"]) self.shd = int(playerData["shd"]) self.shdmax = int(playerData["shdmax"]) self.xp = int(playerData["xp"]) self.honor = int(playerData["honor"]) self.company = int(playerData["company"]) self.level = int(playerData["level"]) self.cloaked = int(playerData["cloaked"]) self.networking = networkingObj self.size = 3 self.color = "white" self.busy = False self.guiObj = self.networking.gui.canvas.create_rectangle( (self.x/100 * self.networking.gui.scale)-self.size, (self.y/100 * self.networking.gui.scale)-self.size, (self.x/100 * self.networking.gui.scale)+self.size, (self.y/100 * self.networking.gui.scale)+self.size, fill=self.color ) self.networking.gui.setText(newText="{0} / {1} \n{2}/{3}\n{4}cr\n{5}uri".format( self.name, self.userID, self.hp, self.shd, self.credits, self.uridium )) print "start hero AI.." self.networking.send("S|CLK") threading._start_new_thread(self.heroAI, ())
def process_imges(self): self.check_files() def execute(self): self.working = True data = ExifOps.batch_job( self.op_path, AccuracyTolerance(self.time_accuracy.get()), LocationPriority(self.time_priority.get()), LocationOverWrite(self.overwrite_policy.get()), OperationType(self.operation.get())) tkMessageBox.showinfo( "Exif Tool", "Total images : {}, found Location for : {}".format( data[0], data[1])) self.working = False threading._start_new_thread(execute, (self, ))
def connect_to_server(name): global client, HOST_PORT, HOST_ADDR try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST_ADDR, HOST_PORT)) client.send(name.encode()) # Send name to server after connecting entName.config(state=tk.DISABLED) btnConnect.config(state=tk.DISABLED) tkMessage.config(state=tk.NORMAL) # start a thread to keep receiving message from server # do not block the main thread :) threading._start_new_thread(receive_message_from_server, (client, "m")) except Exception as e: tk.messagebox.showerror(title="ERROR!!!", message="Cannot connect to host: " + HOST_ADDR + " on port: " + str( HOST_PORT) + " Server may be Unavailable. Try again later")
def update_queue(): for song in queue: if os.path.exists(os.path.join( queue_dir, song + '.wav')) == False and os.path.exists( os.path.join( music_dir, song + '.wav')) == False and os.path.exists( os.path.join(queue_dir, song + '.wav.part')) == False: threading._start_new_thread(get_music, ( song, 'queue', )) if os.path.exists(os.path.join(music_dir, song + 'wav')): print( '\r--- song already downloaded, so not doing it again \n>>> ', end=' ') status_dict[song] = 'downloaded'
def load_json_file(self): if self.working: tkMessageBox.showinfo("Exif Tool", "Wait till current tasks get's finished !") return filename = askopenfile() filename = filename.name def load_data(self, filename): self.working = True DataModel(filename).load_data_map() self.working = False tkMessageBox.showinfo( "Exif Tool", "Data successfully Loaded from {}".format(filename)) threading._start_new_thread(load_data, (self, filename))
def postNotice(userId, title, body, user): newNotice = Messages(subject=title, body=body, PostTime=time.time(), Postman=userId, avater='http://identicon.relucks.org/' + str(random.randint(200, 999)) + '?size=120') msg = flask_mail.Message( recipients=db_getuserByid(userId).email, html=body, subject='网站通知:' + title, ) threading._start_new_thread(send_mail, (msg, )) current_app.logger.info("向" + db_getuserByid(userId).email + "发送了一个通知 标题:" + title + " 内容:" + body) return redirect('/settings/check')
def fetch_metadata(self): # dont repeat if all the data's been already fetched if not self.fetch_type is None: return # doing the url fetch in a thread and sleeping for a while # since the execution of this function takes about 3 to 4 seconds # guess that's how you be lazy print(':::started the url fetch') threading._start_new_thread(self.__fetch_url, ()) time.sleep(2) #self.__fetch_url() if self.__type == 'track_id': track = sp.track(self.track_id) if self.__type == 'name': track_search = sp.search(self.title, type = 'track', limit = 1) if len(track_search ['tracks'] ['items']) <= 0: print(':::track not available from spotify, doing a minimal fetch') if '-' in self.title: self.artists = [self.title.split('-')[0].strip()] else: self.artists = None self.__artists_names = None self.album = None self.track_id = None self.genres = None self.fetch_type = 'minimal' return else: track = track_search ['tracks'] ['items'] [0] self.track_id = track['id'] self.artists = [] self.__artists_names = [] for artist in track['artists']: self.artists.append(Artist(artist_id = artist['id'])) self.__artists_names.append(artist['name']) self.genres = [] for artist in self.artists: for genre in artist.genres: self.genres.append(genre) self.album = Album(album_id = track ['album'] ['id']) self.fetch_type = 'full' print(':::fetched')
def start_server(): global server, HOST_ADDR, HOST_PORT, N btnStart.config(state=tk.DISABLED) btnStop.config(state=tk.NORMAL) HOST_ADDR = END.get() HOST_PORT = int (PORT.get()) N = int (Nl.get()) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #print socket.AF_INET #Socket para com IPV4 #print socket.SOCK_STREAM server.bind((HOST_ADDR, HOST_PORT)) server.listen(5) threading._start_new_thread(accept_clients, (server, " ")) lblHost["text"] = "Endereco: " lblPort["text"] = "Porta: "
def wrapper(*args, **kwargs): gen = f(*args, **kwargs) print('当前线程id:', threading.get_ident()) print('此时的gen_id', id(gen)) gen_long_io = next(gen) def func(): print('当前线程id:', threading.get_ident()) print('此时的gen_id', id(gen)) ret = next(gen_long_io) try: print('执行send操作唤醒生成器') gen.send(ret) except StopIteration: pass threading._start_new_thread(func, ())
def connect_to_server(name): global client, HOST_PORT, HOST_ADDR try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST_ADDR, HOST_PORT)) client.send(name.encode()) # Send name to server after connecting # start a thread to keep receiving message from server # do not block the main thread :) threading._start_new_thread(receive_message_from_server, (client, "m")) top_welcome_frame.pack_forget() top_frame.pack(side=tk.TOP) window_main.title("Tic-Tac-Toe Client - " + name) except Exception as e: tk.messagebox.showerror(title="ERROR!!!", message="Cannot connect to host: " + HOST_ADDR + " on port: " + str(HOST_PORT) + " Server may be Unavailable. Try again later")
def refresh_kbuckets(self): copyTimes = list(self.kBucketRefreshTimes) for i, kBucketRefreshTime in enumerate(copyTimes): if datetime.datetime.now() - kBucketRefreshTime >= datetime.timedelta(seconds=10): # if datetime.datetime.now() - kBucketRefreshTime >= datetime.timedelta(seconds=1): # if datetime.datetime.now() - kBucketRefreshTime >= datetime.timedelta(hours=1): routing_table = self.node.route_table kBucket = routing_table[i] if len(kBucket) == 0: continue rand_idx = random.randrange(0, len(kBucket)) rand_ID = kBucket[rand_idx][0] now = datetime.datetime.now() threading._start_new_thread(self._update_kbucket_time, (rand_idx, now, True)) threading._start_new_thread(self._lookup_and_update, (rand_ID, True))
def upLoad(self, filePathUp, dirPath): # 校验给定的文件路径 if "" == filePathUp.strip() or filePathUp is None: self.__logger_interface.info(u"上传时文件路径为空...") return False # 正则匹配磁盘名 p = re.match(r"[a-zA-Z]:[/\\]", str(dirPath)) if not p: return False filePathUp = u"{}".format(str(filePathUp)) dirPath = u"{}".format(str(dirPath)) if os.path.isfile(filePathUp): # 没有异常,开启线程处理任务 threading._start_new_thread(self.__upThread, (filePathUp, dirPath)) return True else: self.__logger_interface.info(u"不存在该文件...") return False
def connection_thread(*args): root = args[0] retry_count = 0 gui_flag = False while True: try: network = Network('network_thread', '127.0.0.1', 8080) if gui_flag: gui.network = network if not gui_flag: gui = GUI(root, network) logging.log('Connected to the server') gui.update('Connected to the server') gui.update('Enter your name.') break except Exception as e: msg = "[Retry {}] {}".format(retry_count + 1, e) logging.log(msg) retry_count += 1 if retry_count == 1: gui = GUI(root, None) gui.update("Failed to connect the server.\n" +\ "Started retrying.") gui.update("Retry connecting...") time.sleep(5) gui_flag = True elif 4 > retry_count: #logging.log('Retry connecting...') #gui.update("Retry connecting...") time.sleep(5) gui_flag = True elif retry_count == 5: gui.update("Retry limit exceeded.\n" +\ "Unable to connect the server.\n" +\ "Program will automatically exit after 5 sec.") time.sleep(5) gui_flag = True root.destroy() logging.log( 'New thread has been initialized to fetch data from the server') #threading._start_new_thread(network.genRSA, ()) rsa_thread = threading.Thread(target=network.genRSA, args=()) rsa_thread.start() rsa_thread.join() threading._start_new_thread(gui.get_msg, ())
def resolve_iplist(): def do_resolve(host, dnsservers, queue): try: iplist = dns_remote_resolve(host, dnsservers, GC.DNS_BLACKLIST, timeout=2) queue.put((host, dnsservers, iplist or [])) except (socket.error, OSError) as e: logging.error(u'远程解析失败:host=%r,%r', host, e) queue.put((host, dnsservers, [])) # https://support.google.com/websearch/answer/186669?hl=zh-Hans google_blacklist = ['216.239.32.20', '74.125.127.102', '74.125.155.102', '74.125.39.102', '74.125.39.113', '209.85.229.138'] for name, need_resolve_hosts in list(GC.IPLIST_MAP.items()): if name in ('google_gws', 'google_com', 'google_yt', 'google_gs') or all(isip(x) for x in need_resolve_hosts): continue need_resolve_remote = [x for x in need_resolve_hosts if ':' not in x and not isipv4(x)] resolved_iplist = [x for x in need_resolve_hosts if x not in need_resolve_remote] result_queue = Queue.Queue() for host in need_resolve_remote: for dnsserver in GC.DNS_SERVERS: logging.debug(u'远程解析开始:host=%r,dns=%r', host, dnsserver) threading._start_new_thread(do_resolve, (host, [dnsserver], result_queue)) for _ in xrange(len(GC.DNS_SERVERS) * len(need_resolve_remote)): try: host, dnsservers, iplist = result_queue.get(timeout=2) resolved_iplist += iplist or [] logging.debug(u'远程解析成功:host=%r,dns=%s,iplist=%s', host, dnsservers, iplist) except Queue.Empty: logging.warn(u'远程解析超时,尝试本地解析') resolved_iplist += sum([socket.gethostbyname_ex(x)[-1] for x in need_resolve_remote], []) break if name.startswith('google_'): iplist_prefix = re.split(r'[\.:]', resolved_iplist[0])[0] resolved_iplist = list(set(x for x in resolved_iplist if x.startswith(iplist_prefix))) else: resolved_iplist = list(set(resolved_iplist)) if name.startswith('google_'): resolved_iplist = list(set(resolved_iplist) - set(google_blacklist)) if len(resolved_iplist) == 0: logging.warning(u'自定义 host 列表 %r 解析结果为空,请检查你的配置 %r。', name, GC.CONFIG_FILENAME) sys.exit(-1) 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)] logging.info(u'host 列表 %r 解析结果:iplist=%r', name, resolved_iplist) GC.IPLIST_MAP[name] = resolved_iplist