def addJob(self, job, allowQueuing=True): """ Adds a job to the work queue. The job object should have a run() method. If allowQueuing is True (the default), the job will be added to the work queue regardless if there are any idle threads ready. (The only way for there to be no idle threads is if maxThreads is some reasonable, finite limit.) Otherwise, if allowQueuing is False, and there are no more idle threads, the job will not be queued. Returns True if the job was queued, False otherwise. """ self._lock.acquire() try: # Maintain minimum number of spares. while self._idleCount < self._minSpare and self._workerCount < self._maxThreads: self._workerCount += 1 self._idleCount += 1 _thread.start_new_thread(self._worker, ()) # Hand off the job. if self._idleCount or allowQueuing: self._workQueue.append(job) self._lock.notify() return True else: return False finally: self._lock.release()
def run(self): """ Main RegManager thread loop. Periodically checks the update queue and generates topic connections """ #Connect the topics while not self.handler.done and not is_shutdown(): cond = self.cond try: cond.acquire() if not self.updates: cond.wait(0.5) if self.updates: #work from the end as these are the most up-to-date topic, uris = self.updates.pop() #filter out older updates for same topic self.updates = [x for x in self.updates if x[0] != topic] else: topic = uris = None finally: if cond is not None: cond.release() #call _connect_topic on all URIs as it can check to see whether #or not a connection exists. if uris and not self.handler.done: for uri in uris: # #1141: have to multithread this to prevent a bad publisher from hanging us _thread.start_new_thread(self._connect_topic_thread, (topic, uri))
def start(self): input_strings = self.task_input() def run(): try: command_results = [self.run_command(string) for string in input_strings] if not self.cancelled: self.handle_results([result.output() for result in command_results]) # handle errors failed_results = [result for result in command_results if result.returncode] if len(failed_results) > 0: self.show_error_panel(failed_results) finally: self.done = True self.on_done(self) def spin(size, i=0, addend=1): if self.done or self.cancelled: self.view.erase_status('external_command') return before = i % size after = (size - 1) - before self.view.set_status('external_command', '%s [%s=%s]' % (self.cmdline, ' ' * before, ' ' * after)) if not after: addend = -1 if not before: addend = 1 i += addend sublime.set_timeout(lambda: spin(size, i, addend), 100) _thread.start_new_thread(run, ()) spin(8)
def recognise(self, wavpath): audio = None try: # Recognize audio self.logging.info('Recognizing...') r = sr.Recognizer() with sr.AudioFile(wavpath) as source: audio = r.record(source) # read the entire audio file except Exception as ex: return str(ex) self.logging.info('Removing File') _thread.start_new_thread(os.remove, (wavpath,)) command = '' # recognize speech using Sphinx try: command = r.recognize_sphinx(audio) self.logging.info("Sphinx thinks you said " + command) except sr.UnknownValueError: self.logging.info("Sphinx could not understand audio") except sr.RequestError as e: self.logging.info("Sphinx error; {0}".format(e)) return command
def onKeyPressed(self, event): for colour in self.pacmen.keys(): self.pacmen[colour].keyPressed(event) if event.keysym == 'F11': global FULL_SCREEN global LAST_DIMENSIONS self.screen.parent.overrideredirect(not FULL_SCREEN) if FULL_SCREEN: self.screen.parent.geometry(LAST_DIMENSIONS) else: self.screen.parent.geometry("{0}x{1}+0+0".format(self.screen.parent.winfo_screenwidth(), self.screen.parent.winfo_screenheight())) FULL_SCREEN = not FULL_SCREEN LAST_DIMENSIONS = self.screen.parent.geometry() elif event.keysym == 'Return': SOCKET_CLIENT.connect((host, port)) thread.start_new_thread(self.clientLisinter, ()) elif event.keysym == 'BackSpace': global IS_SERVER SOCKET_SERVER.bind((host, port)) IS_SERVER = True thread.start_new_thread(self.waitForOtherClients, ()) else: pass
def tracking_loop(): print("Checking projects. Press ESC to return to menu.") time.sleep(0.5) global loopswitch loopswitch = 'on' _thread.start_new_thread(quit_thread, ()) while True: for projects in sorted(projectdict): url = projectdict[(projects)] pagescrape = requests.get(url) pageparse = bs4.BeautifulSoup(pagescrape.text, "html.parser") backers = pageparse.select('span.pledge__backer-count') if backers[0].getText() == '1,820 backers': print("I checked " + projects + " at " + (str(datetime.datetime.now().time()))[:5]+ ". The slots for early backers were full.") for t in range (60): if loopswitch == 'on': time.sleep(interval/len(projectdict)/60) #reduces loop completion time before return to menu. todo: make '60' dynamic so the user never waits more than 1 second even if they set a long interval. else: return else: print("An early backer slot for " + projects + " is available!") from twilio.rest import TwilioRestClient accountSID = config.get('twilio', 'accountSID') authToken = config.get('twilio', 'authToken') twilioCli = TwilioRestClient(accountSID, authToken) myTwilioNumber = config.get('twilio', 'phoneNumber') targetNumber = config.get('user', 'phoneNumber') message = twilioCli.messages.create(body=config.get('user', 'name') + ': an early backer has pulled out of ' + projects + '!', from_=myTwilioNumber, to=targetNumber) return
def skip_song(self, song): _thread.start_new_thread(self.doubanfm.skip_song, (song.sid, song.aid, self.history, self.reset_songs)) if (song.sid, 's') not in self.history: self.history.insert(0, (song.sid, 's')) if len(self.history) > 20: self.history.pop()
def _on_search_changed_thread(self): """ Just run _reallyon_entry_changed in a thread """ self._timeout = None self._in_thread = True start_new_thread(self._populate, ())
def forward_ports(connection_info): ports = [ connection_info['iopub_port'], connection_info['shell_port'], connection_info['control_port'], connection_info['stdin_port'], connection_info['hb_port'] ] print("Forwarding ports " + str(ports)) for port in ports: _thread.start_new_thread(forward_socket, (port, DASHDBHOST))
def notify_observers(self, data, connection): for observer in self._observers: try: _thread.start_new_thread(observer.__class__.update_on_magic_number, (observer, data, connection)) except Exception: import traceback print (traceback.format_exc())
def __init__(self, f, n, wait_before_exit=False): """ Construct a bunch of `n` threads running the same function `f`. If `wait_before_exit` is True, the threads won't terminate until do_finish() is called. """ self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = not wait_before_exit self.wait_thread = support.wait_threads_exit() self.wait_thread.__enter__() def task(): tid = threading.get_ident() self.started.append(tid) try: f() finally: self.finished.append(tid) while not self._can_exit: _wait() try: for i in range(n): start_new_thread(task, ()) except: self._can_exit = True raise
def add_answer(request): if not request.POST: return redirect(reverse('ask:index')) form = AddAnswerForm(request.POST) if form.is_valid(): question = get_object_or_404(Question, id=form.cleaned_data['question_id']) answer = Answer.objects.create( content=form.cleaned_data['content'], author=request.user, question=question ) anchor = answer.get_anchor() # send notification in new thread _thread.start_new_thread(push_updates, ({ # TODO Must think about render for different people. Onwer and other. 'channel' : question.pk, 'a_id' : question.author.pk, 'common_answer' : render_to_response('ask/includes/answer.html', { 'question' : question, 'answer' : answer, }), 'author_answer' : render_to_response('ask/includes/answer.html', { 'user' : question.author, 'question' : question, 'answer' : answer, }), },)) return redirect(question.get_url_with_answer_anchor(anchor)) try: return redirect(reverse('ask:question-detail', pk=request.POST.get('question_id'))) except: redirect(reverse('ask:index'))
def exec_save_classpath(logger, sbt_cmd, working_dir, classpath_file, callback_fn): """ Run the sbt saveClasspath task (for starting the ensimeProcess) in a seperate thread calling back with the result. :param sbt_cmd: The command for running sbt :param working_dir: The working directory to run in :param classpath_file: Where to write the classpath file to :param callback_fn: The function to call with the classpath (as a string) :return: Nothing """ def worker(): logger.info("Save classpath task running") cmd = sbt_cmd + ["saveClasspath"] output_file_path = os.path.join(working_dir, "saveClasspath.log") with open(output_file_path, "w") as output_file: res = subprocess.call(cmd, cwd=working_dir, stdout=output_file, stderr=subprocess.STDOUT) if res == 0: with open(classpath_file, "r") as f: read_classpath = f.read().replace('\n', '') logger.info("Save classpath task completed successfully") callback_fn(read_classpath) else: logger.info("Save classpath task failed with error " + str(res) + " check " + str(output_file_path)) callback_fn(None) _thread.start_new_thread(worker, ())
def __getMovieName__(): for i in range(30): try: _thread.start_new_thread(__getContent__,(i,)) except: print('process err') input('end')
def jython_reloader(main_func, args, kwargs): from _systemrestart import SystemRestart _thread.start_new_thread(main_func, args) while True: if code_changed(): raise SystemRestart time.sleep(1)
def processMsg(self, msg, sender=...): if msg.getID() == msgs.MSG_SETNAME: sender.setName(msg.name) self.broadcastMsg(msgs.Chat(chat=msg.name + " has joined the debate!")) print("Got name:", msg.name) elif msg.getID() == msgs.MSG_CHAT: print("CHAT:", msg.getChat()) thecolor = {True: 1, False: 4, None: 15}[sender.getTeam()] self.broadcastMsg(msgs.Chat(chat=sender.name + ": " + msg.getChat(), color=thecolor)) elif msg.getID() == msgs.MSG_SETTEAM: print(sender.getName(), "changed team to:", str(msg.getTeam())) sender.setTeam(msg.getTeam()) self.sendMsg(sender, msgs.SetTeam(team=msg.getTeam())) elif msg.getID() == msgs.MSG_SETSUBJ: self.subject = msg.getSubject() print(sender.getName(), "changed the subject to", self.subject) self.broadcastMsg(msg) elif msg.getID() == msgs.MSG_RESETTIMEOUT: self.timeout = msg.getTimeout() thread.start_new_thread(self.runTimer, ())
def run(): try: opts, args = getopt.getopt(sys.argv[1:], "ht") except getopt.error as msg: print(str(msg) + "\n\n" + __doc__, file=sys.stderr) sys.exit() for opt, arg in opts: if opt == "-h": print(__doc__, file=sys.stderr) sys.exit() elif opt == "-t": state.isTest = True state.runTestServer = True state.createWorkers() if state.runTestServer: print("Running a test SMTP server on port 8025...") TestListener() asyncore.loop() else: state.isTest = True state.buildServerStrings() testSocketMap = {} def runTestServer(): TestListener(socketMap=testSocketMap) asyncore.loop(map=testSocketMap) def runProxy(): trainer = SMTPTrainer(Classifier(), state) BayesSMTPProxyListener("localhost", 8025, ("", 8026), trainer) Dibbler.run() _thread.start_new_thread(runTestServer, ()) _thread.start_new_thread(runProxy, ()) sb_test_support.unittest_main(argv=sys.argv + ["suite"])
def _on_list_one_selected(self, selection_list, selected_id): if selected_id == Type.PLAYLISTS: start_new_thread(self._setup_list_playlists, (False,)) self._list_two.clear() self._list_two.show() if not self._list_two.will_be_selected(): self._update_view_playlists(None) elif selected_id < Type.DEVICES: self._list_two.hide() if not self._list_two.will_be_selected(): self._update_view_device(selected_id) elif selected_id in [Type.POPULARS, Type.RECENTS, Type.RANDOMS]: self._list_two.hide() self._update_view_albums(selected_id) elif selected_id == Type.RADIOS: self._list_two.hide() self._update_view_radios() elif selection_list.is_marked_as_artists(): self._list_two.hide() if selected_id == Type.ALL: self._update_view_albums(selected_id) elif selected_id == Type.COMPILATIONS: self._update_view_albums(None, True) else: self._update_view_artists(selected_id, None) else: self._list_two.clear() start_new_thread(self._setup_list_artists, (self._list_two, selected_id, False)) self._list_two.show() if not self._list_two.will_be_selected(): self._update_view_albums(selected_id, False)
def __init__(self): self.players = [] self.timeout = 300 if len(sys.argv) > 1: for index, arg in enumerate(sys.argv): if 'timeout=' in arg: self.timeout = int(arg.split('=')[1]) del sys.argv[index] break if len(sys.argv) < 1: self.subject = "Sample Subject" else: stuf = copy.copy(sys.argv) del stuf[0] self.subject = " ".join(stuf) print("Starting new server on port 5565!") print("Topic is", self.subject) print("Timeout is", self.timeout) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(('', 5565)) thread.start_new_thread(self.getPlayers, ()) thread.start_new_thread(self.runTimer, ())
def _update_view_albums(self, genre_id, is_compilation=False): view = AlbumsView(genre_id, is_compilation) self._stack.add(view) view.show() start_new_thread(view.populate, ()) self._stack.set_visible_child(view) self._stack.clean_old_views(view)
def _update_view_radios(self): view = RadiosView() self._stack.add(view) view.show() start_new_thread(view.populate, ()) self._stack.set_visible_child(view) self._stack.clean_old_views(view)
def _update_list_two(self, updater): update = updater is not None object_id = self._list_one.get_selected_id() if object_id == Type.PLAYLISTS: start_new_thread(self._setup_list_playlists, (update,)) elif self._show_genres and object_id != Type.NONE: self._setup_list_artists(self._list_two, object_id, update)
def show_playlist_manager(self, object_id, genre_id, is_album): view = PlaylistsManageView(object_id, genre_id, is_album, self._stack.get_allocated_width()/2) view.show() self._stack.add(view) self._stack.set_visible_child(view) start_new_thread(view.populate, ())
def connect(self, server, port, nick, user, realname, bindto=("", 0), msgdelay=0.5): if self.connected: self.disconnect("Changing servers") self.channels = {} self.buffer = LineBuffer() self.nickname = nick self.server = server self.port = port self.username = user self.gecos = realname self.msgdelay = msgdelay logger.info("Conectando a {0}:{1}".format(server, port)) try: self.socket = socket.create_connection((server, port), socket.getdefaulttimeout(), bindto) except socket.error as err: logger.error("No se pudo conectar a {0}:{1}: {2}" .format(server, port, err)) return 1 # Comenzamos a procesar la cola.. _thread.start_new_thread(self.process_queue, ()) self.connected = True self._handle_event(Event("connect", None, None)) time.sleep(1) # Le damos tiempo de actuar a los handlers del ircv3 # Nos registramos... self.user(user, realname) self.nick(nick, True) _thread.start_new_thread(self.process_forever, ())
def addwiki(self, bot, cli, ev): if not len(ev.splitd) > 1: cli.privmsg(ev.target, "\00304Error\003: Faltan parametros") c = MonitorWiki2.get(MonitorWiki2.wiki == ev.splitd[1]) if c is False: ch = [] ch.append(ev.splitd[0]) MonitorWiki2.create(wiki=ev.splitd[1], chans=json.dumps(ch)) self.activwikis[ev.splitd[1]] = True c = MonitorWiki2.get(MonitorWiki2.wiki == ev.splitd[1]) _thread.start_new_thread(self.monitorow, (bot, cli, c)) cli.privmsg(ev.target, "Se ha empezado a monitorear" " \2{0}\2 en \2{1}".format(ev.splitd[1], ev.splitd[0])) else: for chan in c.chans: if chan == ev.splitd[0]: cli.privmsg(ev.target, "\00304Error\003: Ya se está monitoreando" "reando esa wiki!") return 1 chans = json.loads(c.chans) chans.append(ev.splitd[0]) c.chans = json.dumps(chans) c.save() cli.privmsg(ev.target, "Se ha empezado a monitorear" " \2{0}\2 en \2{1}".format(ev.splitd[1], ev.splitd[0]))
def __init__(self,camera,driveTrain,params): ''' Constructor ''' #old = -7.6 #number analysis - setpoint 29000, voltage/dec = 11.4/11 hovered at/beneath 29 #analysis - good good good - 1000 error 29000 set -13 max -11.4 voltage -10.8 dec hovered #analysis - 2600, -9.8 voltage, -9.6 dec hovered at 27000 hit the top of the goal woth a new ball #analysis - 24000, -9 voltage -8.7 dec voltage hovered at 24850- #analysis - 24000, -9 voltage -8.7 dec voltage hovered at 24300- hit the bottom of the goal at the back lien of the defense #analysis - 24000, -91 voltage -8.8 dec voltage hovered at 24800- hit the bottom of the goal at the back lien of the defense self.wheelMaxError = 1000 self.testSetpoint = 26650 self.camera = camera self.driveTrain = driveTrain self.maxVoltageSetpoint = -9 self.voltageSetpoint = -9.7 self.decVoltageSetpoint = -9.4 self.motor = wpilib.CANTalon(params) self.motor.enableBrakeMode(True) self.motor.changeControlMode(wpilib.CANTalon.ControlMode.Voltage) self.wasBrake = True self.toggleState = False self.lastToggleTime = 0 self.speed = 0 _thread.start_new_thread( self.periodic, ("Shooter-Update-Thread", "literally nothing",)) self.pdp = powerdistributionpanel.PowerDistributionPanel() self.motor.reverseOutput(False) self.motor.setFeedbackDevice(0)
def multiplyThread(threadNum,searchList): keyLen=len(searchList) start=0 end=0 step=keyLen/threadNum #print(keyLen) temp=() for i in range(threadNum): end=int(start+step) if(end>keyLen): end=keyLen temp=searchList[int(start):end] strs="#".join(temp) temp=(strs,) start=int(end) #print(temp) _thread.start_new_thread(adapter,temp) if end<keyLen: end=int(start+step) if(end>keyLen): end=keyLen temp=searchList[int(start):end] strs="#".join(temp) temp=(strs,) start=int(end) #print(temp) _thread.start_new_thread(adapter,temp)
def show_playlist_editor(self, playlist_name): view = PlaylistEditView(playlist_name, self._stack.get_allocated_width()/2) view.show() self._stack.add(view) self._stack.set_visible_child(view) start_new_thread(view.populate, ())
def run(self): rest_msg = "" try: while True: try: item = self.queue.get_nowait() time.sleep(3) print("stop") self.conn.sendall("stop".encode()) except Empty: dados= self.conn.recv(1024) if dados: data_list = (rest_msg + dados.decode()).split("\n") if len(data_list) > 1: rest_msg = data_list.pop() for data in data_list: try: dados = json.loads(data) if dados: if dados.get("command") == "reader": _thread.start_new_thread(self.read_file, (dados["file"],)) elif dados.get("command") == "write": _thread.start_new_thread(self.write_file, (dados["file"], dados["content"],)) except: print(traceback.format_exc()) except: print(traceback.format_exc()) self.conn.close()
def _update_view_artists(self, artist_id, genre_id): view = ArtistView(artist_id, genre_id) self._stack.add(view) view.show() start_new_thread(view.populate, ()) self._stack.set_visible_child(view) self._stack.clean_old_views(view)
def main_ui(): _thread.start_new_thread(input_ui, ())
def on_client_name_change(self, event): """ Handle EVT_CLIENT_NAME_CHANGE. """ _thread.start_new_thread(self.check_client_for_nick_steal, (event.client, ))
def start(self): """ Initiate a thread to run the XML RPC server. Uses thread.start_new_thread. """ _thread.start_new_thread(self.run, ())
def inputFromKeyboard(): while True: data = input("PROMPT>") if data == "beep": ser.write(BEEP) elif data == 'l': move(100, -100, .05, .2, .25) elif data == 'r': move(-100, 100, .05, .2, .25) elif data == 'f': move(100, 100, .05, .2, .25) elif data == 'b': move(-100, -100, .05, .2, .25) elif data == 's': #stop move(0, 0, 0, 0, .05, .2, .25) else: print("data:", data) num = int(data, 10) print("num", num, "end") c = chr(num) print("char", c, "end") #ser.write(c) ser.write(bytes([num])) ser.flush() if __name__ == "__main__": _thread.start_new_thread(readAll, ()) inputFromKeyboard()
print(f"===Cliente <" ,client ,f"> se ha desconectado.===") # creamos el objeto del socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket creado!") # declaramos el puerto en el que haremos la conexion port = 23451 # ponemos a la escucha al servidor a todas las ips entrantes # al puerto dado s.bind(('', port)) print("socket a la escucha en el puerto: %s" %(port)) # ponemos al socket a escuchar aceptando como maximo 5 usuarios s.listen(5) print("socket escuchando...") print("==========================CONEXIONES=========================") clientes = 0 # bucle de escucha que acepta las peticiones while clientes < 5 : # estableciendo la conexion con el cliente c, addr = s.accept() t.start_new_thread(cliente, (c, addr, clientes)) clientes += 1 # cerrando la conexion (IMPORTANTE o SUSPENDEIS) c.close()
# · kwargs - 可选参数。 import _thread 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: _thread.start_new_thread(print_time, ( "Thread-1", 1, )) _thread.start_new_thread(print_time, ( "Thread-2", 2, )) except: print("Error: 无法启动线程") while 1: pass
def start(self): self._echo('[*] 微信网页版 ... 开动') print() logging.debug('[*] 微信网页版 ... 开动') while True: self._run('[*] 正在获取 uuid ... ', self.getUUID) self._echo('[*] 正在获取二维码 ... 成功') print() logging.debug('[*] 微信网页版 ... 开动') self.genQRCode() print('[*] 请使用微信扫描二维码以登录 ... ') if not self.waitForLogin(): continue print('[*] 请在手机上点击确认以登录 ... ') if not self.waitForLogin(0): continue break self._run('[*] 正在登录 ... ', self.login) self._run('[*] 微信初始化 ... ', self.webwxinit) self._run('[*] 开启状态通知 ... ', self.webwxstatusnotify) self._run('[*] 获取联系人 ... ', self.webwxgetcontact) self._echo('[*] 应有 %s 个联系人,读取到联系人 %d 个' % (self.MemberCount, len(self.MemberList))) print() self._echo('[*] 共有 %d 个群 | %d 个直接联系人 | %d 个特殊账号 | %d 公众号或服务号' % (len(self.GroupList), len(self.ContactList), len(self.SpecialUsersList), len(self.PublicUsersList))) print() self._run('[*] 获取群 ... ', self.webwxbatchgetcontact) self.saveContactList() self.saveGroupMemberList() logging.debug('[*] 微信网页版 ... 开动') if self.DEBUG: print(self) logging.debug(self) if self.interactive and input('[*] 是否开启自动回复模式(y/n): ') == 'y': self.autoReplyMode = True print('[*] 自动回复模式 ... 开启') logging.debug('[*] 自动回复模式 ... 开启') else: print('[*] 自动回复模式 ... 关闭') logging.debug('[*] 自动回复模式 ... 关闭') if sys.platform.startswith('win'): import _thread _thread.start_new_thread(self.listenMsgMode()) else: listenProcess = multiprocessing.Process(target=self.listenMsgMode) listenProcess.start() while True: text = input('') if text == 'quit': listenProcess.terminate() print('[*] 退出微信') logging.debug('[*] 退出微信') exit() elif text[:2] == '->': [name, word] = text[2:].split(':') if name == 'all': self.sendMsgToAll(word) else: self.sendMsg(name, word) elif text[:3] == 'm->': [name, file] = text[3:].split(':') self.sendMsg(name, file, True) elif text[:3] == 'f->': print('发送文件') logging.debug('发送文件') elif text[:3] == 'i->': print('发送图片') [name, file_name] = text[3:].split(':') self.sendImg(name, file_name) logging.debug('发送图片') elif text[:3] == 'e->': print('发送表情') [name, file_name] = text[3:].split(':') self.sendEmotion(name, file_name) logging.debug('发送表情')
### MOUSE INTERACTION ### mouse = Controller() def mouseInteract(x=None, y=None, button=None, pressed=None): global overrideLastUpdateTime, overrideLock if not overrideLock: overrideLastUpdateTime = time.time() + MOUSE_MOVE_IGNORE return def startInteract(): with Listener(on_click=mouseInteract) as listener: listener.join() start_new_thread(startInteract, ()) ### WEBSERVER INTERACTION ### class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(b'') def do_POST(self): global activeWindows path = str(self.path) if path == "/follow":
### [0] Initialize threads params = [] #params.append((lora_connection.loraConnection, lora, data, [], lock)) #params.append((accelerometer.get_data, (None, 2), data, # ("acceleration", "pitch", "roll"), lock)) params.append((thermometer.get_data, None, data, ("temperature_t", "humidity", "dew_point"), lock)) params.append((barometer.get_data, None, data, ("altitude", "temperature_b", "pressure"), lock)) #params.append((lt.light, None, data, ("blue", "red"), lock)) ### [1] Execute threads while True: for param in params: _thread.start_new_thread(functions.threading, param) data["battery"] = py.read_battery_voltage() ### [2] Initialize socket sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) #sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) sock.setblocking(False) ### [3] Wait for threads to finish while data["nFinished"] < len(params): pass ### [4] Format the data and send it #request = functions.formatRequest(data) for i in range(100):
def main_udp(): my_udphost = udp.class_host('127.0.0.1', 61101) _thread.start_new_thread(auto_recv, (my_udphost,)) _thread.start_new_thread(input_udp, ())
if sw1 == sw2 == 1: if sw1_press_flag and sw2_press_flag: if __s12_pressed: _thread.start_new_thread(__s12_pressed, ()) sw1_press_flag = False sw2_press_flag = False elif sw1_press_flag: if __s1_pressed: _thread.start_new_thread(__s1_pressed, ()) sw1_press_flag = False elif sw2_press_flag: if __s2_pressed: _thread.start_new_thread(__s2_pressed, ()) sw2_press_flag = False utime.sleep_ms(20) _thread.start_new_thread(SwitchLoopTask, ()) def pressed(pin, callback): global __s1_pressed, __s2_pressed, __s12_pressed if pin == S12: __s12_pressed = callback elif pin == S1: __s1_pressed = callback elif pin == S2: __s2_pressed = callback
import os def go(thread_name, delay): print(111) count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % (thread_name, time.time())) print("pid:", os.getpid()) print("ppid:", os.getppid()) # 创建两个线程 try: for i in range(10): _thread.start_new_thread(go, ( "thread-1", i, )) _thread.start_new_thread(go, ( "thread-2", 4, )) except: print("Error 启动线程失败") while 1: pass
def determine_active_program_and_wm_class(): global active_process_name global active_wm_class_name active_process_name = active_program_name() active_wm_class_name = active_program_wm_class() while True: event = disp_prog.next_event() if event.type == Xlib.X.PropertyNotify and event.atom == NET_ACTIVE_WINDOW: active_process_name = active_program_name() active_wm_class_name = active_program_wm_class() if x11: _thread.start_new_thread(determine_active_program_and_wm_class, ()) # determine current key modifiers # there must be a better way to do this if x11: display = Display() context = display.record_create_context( 0, [record.AllClients], [{ 'core_requests': (0, 0), 'core_replies': (0, 0), 'ext_requests': (0, 0, 0, 0), 'ext_replies': (0, 0, 0, 0), 'delivered_events': (0, 0), 'device_events': (X.KeyPress, X.KeyRelease), 'errors': (0, 0),
threadedClient.coordData.append("Down") turtle.getcanvas().bind('<Button-1>', appendPenDown, add="+") turtle.getcanvas().bind('<Button1-ButtonRelease>', appendPenUp, add="+") #receive and update other turtle's data #threadedClient.playerX.turtle def updatePlayerX(*args): while True: if (threadedClient.receivedData): coordList = eval(threadedClient.receivedData.decode()) for val in coordList: if (val == "Up"): threadedClient.playerX.turtle.penup() elif (val == "Down"): threadedClient.playerX.turtle.pendown() else: x, y = eval(val) threadedClient.playerX.turtle.goto(x, y) threadedClient.receivedData = None time.sleep(0.3) thread.start_new_thread(updatePlayerX, tuple()) turtle.mainloop()
def gui_solve(): if int(slider_multi.get()) == 1: _thread.start_new_thread(solve, ()) else: solve()
#else: if i % (30 * 60) == 0: print("Valid Internet Connection: " + str(ping())) #s.PAGE=open("/home/pi/index.html", "r").read() nowHour = int(dt.datetime.now().strftime('%H')) #print('hour: ' + str(nowHour)) if (nowHour >= 3 and nowHour < 5 and c.get_boot_duration() > (4 * 60 * 60) and c.ffmpegProg == None): print('Rebooting Pi') os.system('systemctl reboot -i') sun.set_nightvision_setting(False) time.sleep(60) i = i + 1 #limiter = subprocess.Popen(shlex.split("ffmpeg;")) #limiter.wait() print('Starting BirdBoxCamPi') print("Birdbox located at: " + c.get_location().address) camera = c.init() s.camera = camera th.start_new_thread(looping, ("Looper", camera)) start_web_server()
while True: try: print('Connection from', p_client_address) # Receive the data while True: data = p_connection.recv(16) # Turning received data into String info = data.decode("utf-8") info = info.split(",") finalResp = " ,".join( map(str, process(info, matrix, short_matrix))) if data: data = bytes(finalResp, "utf-8") p_connection.sendall(data) else: print("No data from", p_client_address) break finally: # Clean up the connection p_connection.close() while True: # Wait for a connection print("Waiting for a connection") connection, client_address = sock.accept() _thread.start_new_thread(accept_client, (connection, client_address))
def queue_monitor(): try: _thread.start_new_thread(run_queue, ()) except: print("Error: unable to start thread run_queue")
def startJetsonNetworking(): _thread.start_new_thread(server, (IP, RECVPORT)) client(CLIENT, SENDPORT)
def main(): print("starting at:", ctime()) _thread.start_new_thread(loop0, ()) _thread.start_new_thread(loop1, ()) sleep(6) # 阻止主线程继续执行,使得子线程执行完毕后再继续执行下一句代码, 否则两个子线程会将直接终止 print("all DONE at:", ctime())
# setcheckinterval not implemented in IronPython pass try: import _thread except: import _thread as thread def f(): print('new thread') x = 1000000 try: while True: try: _thread.start_new_thread(f, ()) import time time.sleep(.05) except: # not enough memory for another thread print('Failed to create new thread') traceback.print_exc() for i in range(100000): pass except: traceback.print_exc() eval(input())
########################## Main Function ########################### #################################################################### if __name__ == "__main__": option_check() s = socket.socket() # Create a socket object host = '127.0.0.1' # Get local machine name port = int(args[2]) # Reserve a port for your service. print("Server running with id", args[0]) print("Server serving privacy policy", args[1]) print("Listening on port", args[2]) # Broadcast "Alive" status to the Reverse Proxy first connect_reverse_proxy() print("Connecting to the reverse proxy on port", args[3]) # Binds to the port s.bind((host, port)) # Allow 10 clients to connect s.listen(10) # Receive/Process each client connection in a seperate thread while True: c, addr = s.accept() # Establish connection with client. # lock acquired by client print_lock.acquire() print('Received a message from client', addr, "payload") _thread.start_new_thread(on_new_client, (c, addr)) s.close()
_thread.start_new_thread(child, (i, )) if input() == 'q': break parent() def counter(myId, count): for i in range(count): time.sleep(1) print('[%s] => %s' % (myId, i)) for i in range(5): _thread.start_new_thread(counter, (i, 5)) time.sleep(6) print('Main thread exiting.') # namespaces and objects are shared among all threads # one object change can be seen by all, main or child alike # two threads changing one object at the same time might lead to object # corruption # _thread achieves this with *locks* import _thread, time def counter(myId, count): for i in range(count):
def server(host, port): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen(5) while True: _thread.start_new_thread(handle_connection, server.accept())
# test capability to start a thread with keyword args # # SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd # # SPDX-License-Identifier: MIT try: import utime as time except ImportError: import time import _thread def thread_entry(a0, a1, a2, a3): print("thread", a0, a1, a2, a3) # spawn thread using kw args _thread.start_new_thread(thread_entry, (10, 20), {"a2": 0, "a3": 1}) # wait for thread to finish time.sleep(1) # incorrect argument where dictionary is needed for keyword args try: _thread.start_new_thread(thread_entry, (), ()) except TypeError: print("TypeError") print("done")
import _thread def to_print(): global x print(x) x *= 2 print(x) if __name__ == '__main__': x = 5 _thread.start_new_thread(to_print, ())
def run(self): self.path_list = [] self.beacon_path_list = [] self.beacon_block_list = [] self.head_list = ['k-mer'] flist = [] try: for dir, folder, file in os.walk(self.kmc_result_path): if dir == self.kmc_result_path: flist = file for i in list(flist): if i[-11:] == '_beacon.txt': self.beacon_path_list.append( os.path.join(self.kmc_result_path, i)) if i[:-11] + '.txt' not in flist: self.status = -70 self.loginfo = 'Missing some k-mer counting files.' return self.head_list.append(i[:-11]) self.path_list.append( os.path.join(self.kmc_result_path, i[:-11] + '.txt')) self.filesize.append( os.path.getsize( os.path.join(self.kmc_result_path, i[:-11] + '.txt'))) # read kmc files to set Klen ftmp = open( os.path.join(self.kmc_result_path, i[:-11] + '.txt'), 'r') firstline = ftmp.readline().strip() firstline = firstline.split('\t') if self.Klen != -1 and self.Klen != len(firstline[0]): ftmp.close() self.status = -80 self.loginfo = 'K value error.' return else: self.Klen = len(firstline[0]) ftmp.close() except: self.status = -3 self.loginfo = 'Can not open some KMC result files.' return self.KofZ = 'Z' * self.Klen if len(self.beacon_path_list) != len(self.path_list): self.status = -15 self.loginfo = 'Files\' number is wrong.' return # create the temp folder if os.path.exists('temp') == False: os.mkdir('temp') for i in range(self.process_number): self.beacon_block_list.append(round(i * 256 / self.process_number)) # the progress file fprogress = open( os.path.join( 'temp', 'GM_progress' + str(self.beacon_block_list[i]) + ' 0'), 'w') fprogress.close() self.beacon_block_list.append(256) # get each block size fre_sum = [] beacon_point = [[0 for j in range(self.process_number + 1)] for i in range(len(self.path_list))] block_size = [[0 for j in range(len(self.path_list))] for i in range(self.process_number)] for i in range(len(self.path_list)): try: f_beacon = open(self.beacon_path_list[i], 'r') except: self.status = -1 self.loginfo = 'Can not open the K-mer beacon files.' return text = f_beacon.readline().strip() while text != 'beacon:': text = f_beacon.readline().strip() for j in range(self.process_number): if j != 0: for k in range(self.beacon_block_list[j] - self.beacon_block_list[j - 1] - 1): f_beacon.readline().strip() text = f_beacon.readline().strip() beacon_point[i][j] = int(text) try: beacon_point[i][self.process_number] = int(self.filesize[i]) except: self.status = -99 self.loginfo = 'K vaule or Cs value is wrong.' return for j in range(self.process_number): block_size[j][i] = beacon_point[i][j + 1] - beacon_point[i][j] f_beacon.seek(0, 0) text = f_beacon.readline().strip() while text != 'sum:': text = f_beacon.readline().strip() fre_sum.append(int(f_beacon.readline().strip())) f_beacon.close() self.block_size = [sum(n) for n in block_size] # normalization coefficient tmp = -5 for i in range(len(self.path_list)): tmp = max(tmp, len(str(fre_sum[i])) - 4) for i in range(len(self.path_list)): if tmp > 0: fre_sum[i] = fre_sum[i] / (10**tmp) elif tmp < 0: fre_sum[i] = fre_sum[i] * (10**-tmp) # the multiprocess runs process_param = [ self.gm_result_path, self.beacon_path_list, self.path_list, self.Klen, len(self.path_list), self.head_list, self.A_Name, self.A_Number, self.TI_dic, self.KofZ, fre_sum, 4096 ] self.jobs = [ Process(target=get_Son_Matrix, args=(self.beacon_block_list[i], self.beacon_block_list[i + 1] - self.beacon_block_list[i], process_param)) for i in range(self.process_number) ] self.status = 2 _thread.start_new_thread(self.detective_process_ok, ()) for j in self.jobs: j.start() for j in self.jobs: j.join() # rename son matrix j = 0 self.beacon_block_list = self.beacon_block_list[:-1] for i in self.beacon_block_list: try: shutil.move( os.path.join(self.gm_result_path, 'son_matrix_' + str(i) + '.txt'), os.path.join(self.gm_result_path, 'son_matrix_' + str(j) + '.txt')) except: pass j += 1 if self.detective_error() == 0: self.status = 0 time.sleep(1) # wait detective_process_ok to exit
if args.montage: left = w // 4 w = w // 2 tmp = max(32, int(32 / args.scale)) ph = ((h - 1) // tmp + 1) * tmp pw = ((w - 1) // tmp + 1) * tmp padding = (0, pw - w, 0, ph - h) pbar = tqdm(total=tot_frame) skip_frame = 1 if args.montage: lastframe = lastframe[:, left:left + w] write_buffer = Queue(maxsize=500) read_buffer = Queue(maxsize=500) _thread.start_new_thread(build_read_buffer, (args, read_buffer, videogen)) _thread.start_new_thread(clear_write_buffer, (args, write_buffer)) I1 = torch.from_numpy(np.transpose(lastframe, (2, 0, 1))).to( device, non_blocking=True).unsqueeze(0).float() / 255. I1 = pad_image(I1) while True: frame = read_buffer.get() if frame is None: break I0 = I1 I1 = torch.from_numpy(np.transpose(frame, (2, 0, 1))).to( device, non_blocking=True).unsqueeze(0).float() / 255. I1 = pad_image(I1) I0_small = F.interpolate(I0, (32, 32), mode='bilinear',
def show(data=None, host=None, port=None, name=None, debug=False, subprocess=True, data_loader=None, reaper_on=True, open_browser=False, notebook=False, force=False, context_vars=None, ignore_duplicate=False, **kwargs): """ Entry point for kicking off D-Tale :class:`flask:flask.Flask` process from python process :param data: data which D-Tale will display :type data: :class:`pandas:pandas.DataFrame` or :class:`pandas:pandas.Series` or :class:`pandas:pandas.DatetimeIndex` or :class:`pandas:pandas.MultiIndex`, optional :param host: hostname of D-Tale, defaults to 0.0.0.0 :type host: str, optional :param port: port number of D-Tale process, defaults to any open port on server :type port: str, optional :param name: optional label to assign a D-Tale process :type name: str, optional :param debug: will turn on :class:`flask:flask.Flask` debug functionality, defaults to False :type debug: bool, optional :param subprocess: run D-Tale as a subprocess of your current process, defaults to True :type subprocess: bool, optional :param data_loader: function to load your data :type data_loader: func, optional :param reaper_on: turn on subprocess which will terminate D-Tale after 1 hour of inactivity :type reaper_on: bool, optional :param open_browser: if true, this will try using the :mod:`python:webbrowser` package to automatically open your default browser to your D-Tale process :type open_browser: bool, optional :param notebook: if true, this will try displaying an :class:`ipython:IPython.display.IFrame` :type notebook: bool, optional :param force: if true, this will force the D-Tale instance to run on the specified host/port by killing any other process running at that location :type force: bool, optional :param context_vars: a dictionary of the variables that will be available for use in user-defined expressions, such as filters :type context_vars: dict, optional :param ignore_duplicate: if true, this will not check if this data matches any other data previously loaded to D-Tale :type ignore_duplicate: bool, optional :Example: >>> import dtale >>> import pandas as pd >>> df = pandas.DataFrame([dict(a=1,b=2,c=3)]) >>> dtale.show(df) D-Tale started at: http://hostname:port ..link displayed in logging can be copied and pasted into any browser """ global ACTIVE_HOST, ACTIVE_PORT, USE_NGROK try: logfile, log_level, verbose = map(kwargs.get, ['logfile', 'log_level', 'verbose']) setup_logging(logfile, log_level or 'info', verbose) if USE_NGROK: if not PY3: raise Exception( 'In order to use ngrok you must be using Python 3 or higher!' ) from flask_ngrok import _run_ngrok ACTIVE_HOST = _run_ngrok() ACTIVE_PORT = None else: initialize_process_props(host, port, force) url = build_url(ACTIVE_PORT, ACTIVE_HOST) instance = startup(url, data=data, data_loader=data_loader, name=name, context_vars=context_vars, ignore_duplicate=ignore_duplicate) is_active = not running_with_flask_debug() and is_up(url) if is_active: def _start(): if open_browser: instance.open_browser() else: if USE_NGROK: thread = Timer(1, _run_ngrok) thread.setDaemon(True) thread.start() def _start(): app = build_app(url, reaper_on=reaper_on, host=ACTIVE_HOST) if debug and not USE_NGROK: app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True else: getLogger("werkzeug").setLevel(LOG_ERROR) if open_browser: instance.open_browser() # hide banner message in production environments cli = sys.modules.get('flask.cli') if cli is not None: cli.show_server_banner = lambda *x: None if USE_NGROK: app.run(threaded=True) else: app.run(host='0.0.0.0', port=ACTIVE_PORT, debug=debug, threaded=True) if subprocess: if is_active: _start() else: _thread.start_new_thread(_start, ()) if notebook: instance.notebook() else: logger.info('D-Tale started at: {}'.format(url)) _start() return instance except DuplicateDataError as ex: print( 'It looks like this data may have already been loaded to D-Tale based on shape and column names. Here is ' 'URL of the data that seems to match it:\n\n{}\n\nIf you still want to load this data please use the ' 'following command:\n\ndtale.show(df, ignore_duplicate=True)'. format( DtaleData(ex.data_id, build_url(ACTIVE_PORT, ACTIVE_HOST)).main_url())) return None
def start_advertising(self): _thread.start_new_thread(self._adv_worker, ())