else: server.tcp_main(sys.argv[1], sys.argv[3]+'/' if sys.argv[3][len(sys.argv[3])-1]!='/' else sys.argv[3]) def start_udp_server(threadName): print 'Started UDP server' if len(sys.argv) < 4: server.udp_main(sys.argv[1], 'Share/') #The folder I share with other clients else: server.udp_main(sys.argv[1], sys.argv[3]+'/' if sys.argv[3][len(sys.argv[3])-1]!='/' else sys.argv[3]) def start_client(threadName): print 'Started client' if len(sys.argv) < 4: client.main(sys.argv[2], 'ShareDown/') #My downloads get downloaded here else: client.main(sys.argv[2], sys.argv[3]+'/' if sys.argv[3][len(sys.argv[3])-1]!='/' else sys.argv[3]) t1 = Thread( target=start_tcp_server, args=("Server1", ) ) t1.daemon = True t1.start() time.sleep(1) t2 = Thread( target=start_udp_server, args=("Server2", ) ) t2.daemon = True t2.start() time.sleep(1) t3 = Thread( target=start_client, args=("Client", ) ) t3.start() t3.join() sys.exit()
def __init__(self): rospy.init_node("Hackathon") t = Thread(target=self.ros) t.start() Window.sure.display(0)
def registerEvent(self,eventName,generator,interval): thread = Thread(target=self.iterate, args=(eventName,generator,interval)) self.threads.append(thread) thread.start()
def main(): """ def f1(name): print('hello', name) th = Thread(target=f1, args=('Bob',)) th.start() th.join() class PrintThread(Thread): def __init__(self, name): super().__init__() self.name = name def run(self): print('hello', self.name) th = PrintThread('Mike') th.start() th.join() from concurrent.futures import ThreadPoolExecutor, as_completed def f2(a): return a * a # .shutdown() in exit with ThreadPoolExecutor(max_workers=3) as pool: results = [pool.submit(f2, i) for i in range(10)] for future in as_completed(results): print(future.result(), end=' ') """ """ Threads synchronization """ """ from queue import Queue def worker(q, n): while True: item = q.get() if item is None: break print('process data', n, item) q = Queue(5) th1 = Thread(target=worker, args=(q, 1)) th2 = Thread(target=worker, args=(q, 2)) th1.start() th2.start() for i in range(50): q.put(i) # stops threads q.put(None) q.put(None) th1.join() th2.join() import threading class Point(object): def __init__(self): self._mutex = threading.RLock() self._x = 0 self._y = 0 def get(self): with self._mutex: return (self._x, self._y) def set(self, x, y): with self._mutex: self._x = x self._y = y a = threading.RLock() b = threading.RLock() def foo(): try: a.acquire() # get lock b.acquire() finally: a.release() b.release() class Queue: def __init(self, size=5): self._size = size self._queue = [] self._mutex = threading.RLock() self._empty = threading.Condition(self._mutex) self._full = threading.Condition(self._mutex) def put(self, val): with self._full: while len(self._queue) >= self._size: self._full.wait() self._queue.append(val) self._empty.notify() def get(self): with self._empty: while len(self._queue) == 0: self._empty.wait() ret = self._queue.pop(0) self._full.notify() return ret """ """ Global Interpreter Lock GIL for memory guarding """ from threading import Thread import time def count(n): while n > 0: n -= 1 # series run t0 = time.time() count(100_000_00) count(100_000_00) print('Series run: ', time.time() - t0) # parallel run t0 = time.time() th1 = Thread(target=count, args=(100_000_000,)) th2 = Thread(target=count, args=(100_000_000,)) th1.start(); th2.start() th1.join(); th2.join() print('Parallel run: ', time.time() - t0) # if program needs only cpu resources, it will work more slowly with # multi-threads than with one thread (linear implementation) """
def trigger_scraper(scraper): thread = Thread(target=scraper.scrape, args=()) thread.start()
if __name__ == "__main__": print('Initializing') rospy.init_node("threadripper") # initialize the publishers PRIOR to running the # threads # use 'rotopic echo /t1' to view thread1's output # use 'rostopic echo/t2' to view thread2's output pub1 = rospy.Publisher("/t1", String, queue_size=2) pub2 = rospy.Publisher("/t2", String, queue_size=2) print('Launching threads') # Creat the threads, pass in a useless argument t1 = Thread(target=function1, args=(10,)) t2 = Thread(target=function2, args=(10,)) # Let the games begin! t1.start() t2.start() # Wait for a CTRL-C or a roslaunch kill (IMPORTANT) while not rospy.is_shutdown(): pass # Tell the threads to die kill = True # wait for the threads to terminate t1.join()
v, o, c, h, l = r['v'], r['o'], r['c'], r[ 'h'], r['l'] bars.append([v, o, c, h, l]) if len(bars) > 0: print(f'Got Postmarket {sym} {day}') dump_bin(f'postmarket/{sym}/{day}', bars) except: pass if __name__ == '__main__': sortedymbols = sorted(symbols) us_holidays = holidays.UnitedStates() dates = [datetime.today() - timedelta(days=i) for i in range(2, 4)] get_bars(symbols, dates) dates = sorted([ str(date).split(' ')[0] for date in dates if date not in us_holidays and date.isoweekday() in range(1, 6) ]) loop = asyncio.get_event_loop() loop.run_until_complete(main(symbols, dates)) Thread(target=post_market_index, args=(dates[0], )).start() Thread(target=premarket_index, args=(dates[0], )).start() Thread(target=post_market_index, args=(dates[0], )).start() Thread(target=premarket_sym, args=(sortedymbols, dates[0])).start() Thread(target=post_market_sym, args=(sortedymbols, dates[0])).start()
def hello(): while True: now=datetime.now() currentTime=now.strftime("%I:%M:%S %p") currentDate=now.strftime("%b, %d %Y") ui.lblTime.setText(currentTime) ui.lblDate.setText(currentDate) # time.sleep(5) print('hello') if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() now=datetime.now() currentTime=now.strftime("%I:%M:%S %p") currentDate=now.strftime("%b, %d %Y") ui.lblTime.setText(currentTime) ui.lblDate.setText(currentDate) t = Thread(target=hello) t.start() sys.exit(app.exec_())
def _start_background_process(self, clean=None, extra_args=[]): # deque, because in one occasion I need to put messages back self._response_queue = collections.deque() # prepare environment env = get_environment_for_python_subprocess(self._executable) # variables controlling communication with the back-end process env["PYTHONIOENCODING"] = "utf-8" # because cmd line option -u won't reach child processes # see https://github.com/thonny/thonny/issues/808 env["PYTHONUNBUFFERED"] = "1" # Let back-end know about plug-ins env["THONNY_USER_DIR"] = THONNY_USER_DIR env["THONNY_FRONTEND_SYS_PATH"] = repr(sys.path) env["THONNY_LANGUAGE"] = get_workbench().get_option("general.language") if thonny.in_debug_mode(): env["THONNY_DEBUG"] = "1" elif "THONNY_DEBUG" in env: del env["THONNY_DEBUG"] if not os.path.exists(self._executable): raise UserError( "Interpreter (%s) not found. Please recheck corresponding option!" % self._executable ) cmd_line = ( [ self._executable, "-u", # unbuffered IO "-B", # don't write pyo/pyc files # (to avoid problems when using different Python versions without write permissions) ] + self._get_launcher_with_args() + extra_args ) creationflags = 0 if running_on_windows(): creationflags = subprocess.CREATE_NEW_PROCESS_GROUP debug("Starting the backend: %s %s", cmd_line, get_workbench().get_local_cwd()) extra_params = {} if sys.version_info >= (3, 6): extra_params["encoding"] = "utf-8" self._proc = subprocess.Popen( cmd_line, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self._get_launch_cwd(), env=env, universal_newlines=True, creationflags=creationflags, **extra_params ) # setup asynchronous output listeners Thread(target=self._listen_stdout, args=(self._proc.stdout,), daemon=True).start() Thread(target=self._listen_stderr, args=(self._proc.stderr,), daemon=True).start()
def start(self): Thread(target=self.update, args=()).start() return self
""" thread2.py 线程函数传参 """ from threading import Thread from time import sleep # 含有参数的线程函数 def fun(sec,name): print("含有参数的线程") sleep(sec) print("%s执行完毕"%name) # 创建多个线程 jobs = [] for i in range(5): t = Thread(target=fun,args=(2,),kwargs={'name':"T%d"%i}) jobs.append(t) # 存储线程对象 t.start() for i in jobs: i.join()
def run_loop(self): if self.thread is None: self.thread = Thread(target=self.loop) self.thread.start()
def add(self, ip_address, port, handler): httpd = ThreadedHTTPServer((ip_address, port), handler) self._threads.append((Thread(target=__run__, args=[httpd]), httpd))
def start_high_level_thread(): thread = Thread(target=thread_func, args=(10, )) thread.start() # thread.join() print("high level thread finished...exiting\n")
def dispatch ( self, handler, *args ): Thread( target = handler, args = args ).start()
# threshold, and if so, increment the blink frame counter if ear < EYE_AR_THRESH: COUNTER += 1 # if the eyes were closed for a sufficient number of frames/time # then sound the alarm if COUNTER >= EYE_AR_CONSEC_FRAMES: # if the alarm is not on, turn it on if not ALARM_ON: ALARM_ON = True # check to see if an alarm file was supplied, # and if so, start a thread to have the alarm # sound played in the background if args["alarm"] == "": t = Thread(target=sound_alarm, args=(args["alarm"], )) t.daemon = True t.start() # draw an alarm on the frame cv2.putText(frame, "DISTRACTION ALERT!", (400, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # otherwise, the eye aspect ratio is not below the blink # threshold, so reset the counter and alarm else: COUNTER = 0 ALARM_ON = False # draw the computed eye aspect ratio on the frame to help # with debugging and setting the correct eye aspect ratio
gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info run = True running = False logging_event = True logstate = False logging = LOG_AT_START #show_state(logging) batch_data = [] #for new filenames each command #filename = "log/"+"Log-"+str(datetime.now())+".csv" #file_setup(filename) if DELAY > 0: Thread(target=timed_log).start() while run == True: ledrotate = 0 sense_data = get_sense_data() #gpsd.next() #get the latest GPS data from GPSD help with delays #logging_event, run = check_input() #logging_event = logging #logging_event,run = check_inputj() # causes a crash #logging_event = logging if logging_event and logging: logging = False
time.sleep(0.1) while True: result = lock2.acquire(timeout=1) if result: print("线程1 锁住了lock2") print("线程1 你好") lock2.release() break #lock1.release() else: lock1.release() def f2(): lock2.acquire() print("线程2 锁住lock2") time.sleep(0.1) lock1.acquire() print("线程2 锁住了lock1") print("线程2 你好") lock1.release() lock2.release() t1 = Thread(target=f1) t2 = Thread(target=f2) t1.start() t2.start() t1.join() t2.join()
JOBS = 28 st = time.time() def do_somthing_using(url): page = urllib2.urlopen(url[0]).read() location = page.index('Total Hours') totalHours = page[location + 31:location + 37] TempList.append([url[1], totalHours]) def working(): for url in urls: do_somthing_using(url) q.task_done() time.sleep(1) for i in range(NUM): t = Thread(target=working) t.setDaemon(True) t.start() for i in range(JOBS): q.put(i) q.join() now = time.strftime("%Y%m%d") w = csv.writer(file('xxx hours by %s.csv' % now, 'wb')) w.writerows(TempList)
def main(): # import the necessary packages from scipy.spatial import distance as dist from imutils.video import FileVideoStream from imutils.video import VideoStream from imutils import face_utils from threading import Thread import playsound import numpy as np import argparse import imutils import time import dlib import cv2 def sound_alarm(path): # play an alarm sound playsound.playsound(path) def eye_aspect_ratio(eye): # compute the euclidean distances between the two sets of # vertical eye landmarks (x, y)-coordinates A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) # compute the euclidean distance between the horizontal # eye landmark (x, y)-coordinates C = dist.euclidean(eye[0], eye[3]) # compute the eye aspect ratio ear = (A + B) / (2.0 * C) # return the eye aspect ratio return ear # construct the argument parse and parse the arguments # ap = argparse.ArgumentParser() # ap.add_argument("-p", "--shape-predictor", required=True, # help="path to facial landmark predictor") # ap.add_argument("-a", "--alarm", type=str, default="", # help="path alarm .WAV file") # ap.add_argument("-w", "--webcam", type=int, default=0, # help="index of webcam on system") # args = vars(ap.parse_args()) # print (args) # define two constants, one for the eye aspect ratio to indicate # blink and then a second constant for the number of consecutive # frames the eye must be below the threshold EYE_AR_THRESH = 0.3 EYE_AR_CONSEC_FRAMES = 3 # initialize the frame counters and the total number of blinks COUNTER = 0 ALARM_ON = False # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor print("[INFO] loading facial landmark predictor...") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # grab the indexes of the facial landmarks for the left and # right eye, respectively (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"] (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"] # start the video stream thread print("[INFO] starting video stream thread...") # vs = FileVideoStream(args["video"]).start() fileStream = True vs = VideoStream(src=0).start() # vs = VideoStream(usePiCamera=True).start() fileStream = False time.sleep(1.0) # loop over frames from the video stream while True: # if this is a file video stream, then we need to check if # there any more frames left in the buffer to process if fileStream and not vs.more(): break # grab the frame from the threaded video file stream, resize # it, and convert it to grayscale # channels) frame = vs.read() frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # detect faces in the grayscale frame rects = detector(gray, 0) # loop over the face detections for rect in rects: # determine the facial landmarks for the face region, then # convert the facial landmark (x, y)-coordinates to a NumPy # array shape = predictor(gray, rect) shape = face_utils.shape_to_np(shape) # extract the left and right eye coordinates, then use the # coordinates to compute the eye aspect ratio for both eyes leftEye = shape[lStart:lEnd] rightEye = shape[rStart:rEnd] leftEAR = eye_aspect_ratio(leftEye) rightEAR = eye_aspect_ratio(rightEye) # average the eye aspect ratio together for both eyes ear = (leftEAR + rightEAR) / 2.0 # compute the convex hull for the left and right eye, then # visualize each of the eyes leftEyeHull = cv2.convexHull(leftEye) rightEyeHull = cv2.convexHull(rightEye) cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1) cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1) # check to see if the eye aspect ratio is below the blink # threshold, and if so, increment the blink frame counter if (ear < EYE_AR_THRESH): COUNTER += 1 # if the eyes were closed for a sufficient number of # then sound the alarm if COUNTER >= EYE_AR_CONSEC_FRAMES: # if the alarm is not on, turn it on if not ALARM_ON: ALARM_ON = True # check to see if an alarm file was supplied, # and if so, start a thread to have the alarm # sound played in the background if "alarm.wav" != "": t = Thread(target=sound_alarm, args=("alarm.wav",)) t.deamon = True t.start() # draw an alarm on the frame cv2.putText(frame, "DROWSINESS ALERT!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # otherwise, the eye aspect ratio is not below the blink # threshold else: # reset the eye frame counter COUNTER = 0 ALARM_ON = False # draw the computed eye aspect ratio on the frame to help # with debugging and setting the correct eye aspect ratio # thresholds and frame counters cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # show the frame cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if (key == ord("q")): break # do a bit of cleanup cv2.destroyAllWindows() vs.stop()
def start(self): self.finish_flag = False self.thread_monitoring_button_state = Thread(target=self.monitoring_button_state) self.thread_monitoring_button_state.start()
def _init_thread(self, target, *args, **kwargs): thr = Thread(target=target, args=args, kwargs=kwargs) thr.start()
def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True): self.mode = 'stream' self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources) as f: sources = [ x.strip() for x in f.read().strip().splitlines() if len(x.strip()) ] else: sources = [sources] n = len(sources) self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [ 0 ] * n, [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later self.auto = auto for i, s in enumerate(sources): # index, source # Start thread to read frames from video stream st = f'{i + 1}/{n}: {s}... ' if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video check_requirements(('pafy', 'youtube_dl')) import pafy s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam cap = cv2.VideoCapture(s) assert cap.isOpened(), f'{st}Failed to open {s}' w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback _, self.imgs[i] = cap.read() # guarantee first frame self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) LOGGER.info( f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)" ) self.threads[i].start() LOGGER.info('') # newline # check for common shapes s = np.stack([ letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs ]) self.rect = np.unique( s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: LOGGER.warning( 'WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.' )
def run(self): t = Thread(target=self.runner) t.daemon = True t.start()
def countThread(self): self.twice = False self.t3 = Thread(target=self.countDown) self.t3.start()
elif event.key == pygame.K_SPACE : rob.Taunt() elif event.key == pygame.K_d : rob.Damaged() elif event.key == pygame.K_f : rob.Firing() if event == pygame.QUIT: pygame.quit() sys.exit() kp =False terrains.clear(screen,background) robots.clear(screen,background) terrains.update() robots.update() terrains.draw(screen) robots.draw(screen) pygame.display.flip() #GUI_main_loop() def lancer_partie(): land = c.Terrain('window_test.txt') partie = c.Game(land) Thread(target = lancer_partie()).start() #Thread(target = hello()).start()
def payed(self): self.t2=Thread(target=self.payedMessage) self.t2.start()
for ins in range(len(self.inputs[:3])): if gp.input(self.inputs[ins]): gp.output(self.outputs[ins], gp.LOW) time.sleep(2.5) gp.output(self.outputs[ins], gp.HIGH) else: gp.output(self.outputs[ins], gp.HIGH) ## def showSws(self): ## upset = gp.input(self.up) ## dnset = gp.input(self.dn) ## print("UP switch(13) is ", upset) ## print("DN switch(26) is ", dnset) if __name__ == '__main__': s = SwitchWatch() thread = Thread(target=s.scanSws) thread.start() try: while True: print "hi" time.sleep(1) except KeyboardInterrupt: thread.join() gp.cleanup()
def __init__(self, servidor): self.servidor = servidor thread_personagens = Thread(target= self.run, args=()) thread_personagens.daemon = True thread_personagens.start() ThreadUpdate.threads.append(thread_personagens)
def thread_lock_demo(tn=5): for i in range(tn): t = Thread(target=worker_func_lock, args=[gSemaphore]) t.start()