当前位置: 首页>>代码示例>>Python>>正文


Python Thread.start方法代码示例

本文整理汇总了Python中threading.Thread.start方法的典型用法代码示例。如果您正苦于以下问题:Python Thread.start方法的具体用法?Python Thread.start怎么用?Python Thread.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Thread的用法示例。


在下文中一共展示了Thread.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: do_main_program

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def do_main_program():
	
	do_scheduler()

	# read config and init sensors
	
	global sensors
	sensors = config.readConfig()
	
	logger.debug(sensors.keys())

	
	
	
	threadHTTP = Thread(target=inetServer.threadHTTP)
	threadHTTP.setDaemon(True)
	threadHTTP.start()

	
	while 1:
		try:
			time.sleep(0.1)
		except KeyboardInterrupt:
			print >> sys.stderr, '\nExiting by user request.\n'
			sys.exit(0)
开发者ID:jtonk,项目名称:Digit,代码行数:27,代码来源:digit.py

示例2: runWorker

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def runWorker(w, args, checklist, quithooks, queue=None):
    global killed
    global workers
    
    thrdRun = Thread(target=run, args=(w, args))
    thrdRun.daemon = True
    
    thrdRun.start()
    time.sleep(1)
    
    while (w.hasLines() or not w.isDone()) and not killed:
        line = w.nextLine()
        
        if line != None:
            message("Line", "Out", line.strip(), False)
            logLine(line)
            
            if maintainChecklist(w, checklist, line):
                if isChecklistDone(checklist):
                    message(w.fullName(), "Run complete", "Moving into background")
                    break
            else:
                if checkQuitHooks(w, quithooks, line):
                    globalKill()
        
        if queue:
            try:
                queued_command = queue.get_nowait()
                
                if queued_command == "quit":
                    w.kill()
                    queue.put("ok")
            except Empty:
                pass
开发者ID:code-iai,项目名称:longterm_fetch_and_place,代码行数:36,代码来源:continuous.py

示例3: loop

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
	def loop(self):
		if self.authorization_failed: return
		super(GetworkSource, self).loop()

		thread = Thread(target=self.long_poll_thread)
		thread.daemon = True
		thread.start()

		while True:
			if self.should_stop: return

			if self.check_failback():
				return True

			try:
				with self.switch.lock:
					miner = self.switch.updatable_miner()
					while miner:
						work = self.getwork()
						self.queue_work(work, miner)
						miner = self.switch.updatable_miner()

				self.process_result_queue()
				sleep(1)
			except Exception:
				say_exception("Unexpected error:")
				break
开发者ID:AngelMarc,项目名称:poclbm,代码行数:29,代码来源:GetworkSource.py

示例4: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
    def __init__(self, n_threads):

        self.n_threads = n_threads

        self._running = True

        self.input_queues = []
        self.output_queues = []
        self.exception_queues = []
        self.threads = []
        for i in range(n_threads):
            input_queue = queue.Queue()
            output_queue = queue.Queue()
            exception_queue = queue.Queue()
            thread = Thread(
                    target=self._thread_func,
                    args=(input_queue, output_queue, exception_queue))
            thread.daemon = True

            self.input_queues.append(input_queue)
            self.output_queues.append(output_queue)
            self.exception_queues.append(exception_queue)
            self.threads.append(thread)

            thread.start()
开发者ID:andrewpaulreeves,项目名称:soapy,代码行数:27,代码来源:numbalib.py

示例5: AntiFlapping

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
class AntiFlapping(object):
    """
    AntiFlapping class to process event in a timely maneer
    """
    def __init__(self, window):
        self.window = window
        self.tasks = Queue(maxsize=1)
        self._window_ended = True
        self._thread = Thread(name="AntiFlapping", target=self._run)
        self._thread.start()

    def newEvent(self, func, kwargs={}):
        """
        newEvent Triggered.
        """
        if not self.tasks.full() and self._window_ended:
            self.tasks.put({'func': func, 'args':kwargs})

    def _run(self):
        """
        internal runloop that will fire tasks in order.
        """
        while True:
            task = self.tasks.get()
            self._window_ended = False
            sleep(self.window)
            self._window_ended = True
            if task['args']:
                task['func'](**task['args'])
            else:
                task['func']()
开发者ID:CyrilPeponnet,项目名称:Unify,代码行数:33,代码来源:switchboard.py

示例6: Watch

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def Watch( Module, Callback, * Args, ** Kwds ):
  if Module.__file__ in WatchList:
    return

  T = Thread(target = WatchThread, args=(Module,Callback,Args,Kwds))
  T.setDaemon(True)
  T.start()
开发者ID:amercader,项目名称:MapFish-Print-IIS,代码行数:9,代码来源:Watch.py

示例7: send_async

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
 def send_async(cls, port, message):
     """ Starts a new thread which sends a given message to a port """
     thread = Thread(target=cls.__send_message_async, args=(port, message),
                     name="NC-SendAsync")
     thread.setDaemon(True)
     thread.start()
     return thread
开发者ID:croxis,项目名称:SpaceDrive,代码行数:9,代码来源:network_communication.py

示例8: eject_windows

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
    def eject_windows(self):
        from calibre.constants import plugins
        from threading import Thread
        winutil, winutil_err = plugins['winutil']
        drives = []
        for x in ('_main_prefix', '_card_a_prefix', '_card_b_prefix'):
            x = getattr(self, x, None)
            if x is not None:
                drives.append(x[0].upper())

        def do_it(drives):
            for d in drives:
                try:
                    winutil.eject_drive(bytes(d)[0])
                except Exception as e:
                    try:
                        prints("Eject failed:", as_unicode(e))
                    except:
                        pass

        def do_it2(drives):
            import win32process
            subprocess.Popen([eject_exe()] + drives, creationflags=win32process.CREATE_NO_WINDOW).wait()

        t = Thread(target=do_it2, args=[drives])
        t.daemon = True
        t.start()
        self.__save_win_eject_thread = t
开发者ID:mching,项目名称:calibre,代码行数:30,代码来源:device.py

示例9: checkTimeOutPut

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def checkTimeOutPut(args):
    global currCommandProcess
    global stde
    global stdo
    stde = None
    stdo = None
    def executeCommand():
        global currCommandProcess
        global stdo
        global stde
        try:
            stdo, stde = currCommandProcess.communicate()
            printLog('stdout:\n'+str(stdo))
            printLog('stderr:\n'+str(stde))
        except:
            printLog("ERROR: UNKNOWN Exception - +checkWinTimeOutPut()::executeCommand()")

    currCommandProcess = subprocess.Popen(args,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    thread = Thread(target=executeCommand)
    thread.start()
    thread.join(TIMOUT_VAL) #wait for the thread to complete 
    if thread.is_alive():
        printLog('ERROR: Killing the process - terminating thread because it is taking too much of time to execute')
        currCommandProcess.kill()
        printLog('ERROR: Timed out exception')
        raise errorHandler.ApplicationException(__file__, errorHandler.TIME_OUT)
    if stdo == "" or stdo==None:
        errCode = currCommandProcess.poll()
        printLog('ERROR: @@@@@Raising Called processor exception')
        raise subprocess.CalledProcessError(errCode, args, output=stde)
    return stdo
开发者ID:CGAnderson,项目名称:Bolt,代码行数:33,代码来源:commonPerformance.py

示例10: footpedal_handler

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def footpedal_handler(data):
    global instruments
    global selected_instrument_index

    left_pedal_pressed = data[1] & 1
    middle_pedal_pressed = data[1] & 2
    right_pedal_pressed = data[1] & 4

    if (left_pedal_pressed):
        # Release the currently selected instrument.
        # This will cause the run_instrument background thread for that instrument
        # to exit because the instrument handle will be invalid.
        current_instrument = instruments[selected_instrument_index]
        current_instrument.release();

        # Cycle to the next instrument
        selected_instrument_index = (selected_instrument_index + 1) % len(instruments)

        # Once we have our new instrument, acquire a handle and start using it.
        current_instrument = instruments[selected_instrument_index]
        current_instrument.acquire()
        thread = Thread(target=background_worker, args=(current_instrument,))
        thread.start()
    if (middle_pedal_pressed or right_pedal_pressed) :
        text_to_speech_async("pedal functionality not defined")
开发者ID:armstrap,项目名称:armstrap-pyvirtualbench,代码行数:27,代码来源:hands_free_dmm.py

示例11: Client

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
class Client(QObject):

    new_message = pyqtSignal(str)

    def __init__(self, username, server="localhost", send_port="5557", recv_port="5556"):
        QObject.__init__(self)
        self.username = username
        self.context = zmq.Context()

        #Sender socket using PULL-PUSH pattern
        self.sender_socket = self.context.socket(zmq.PUSH)
        self.sender_socket.connect("tcp://{0}:{1}".format(server, send_port))

        #Receiver socket using SUB_PUB pattern
        self.receiver_socket = self.context.socket(zmq.SUB)
        self.receiver_socket.connect("tcp://{0}:{1}".format(server, recv_port))
        self.receiver_socket.setsockopt(zmq.SUBSCRIBE, b"")

        #Start receiver thread
        self.recv_thread = Thread(target=self.receive, daemon=True)
        self.recv_thread.start()

    def receive(self):
        while True:
            #Get the publisher's message
            message = self.receiver_socket.recv()
            self.new_message.emit(str(message))

    def send(self, message):
        message = "{0} says: {1}".format(self.username, message)
        self.sender_socket.send(message.encode())
开发者ID:carlgonz,项目名称:zmq_examples,代码行数:33,代码来源:Client.py

示例12: _move

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
    def _move(self, pos, velocity, acceleration, deceleration, relative, block, units):
        if velocity is None:
            velocity = self.initial_velocity

        if acceleration is None:
            acceleration = self.acceleration
        if deceleration is None:
            deceleration = self.deceleration

        pos = self._get_steps(pos, units)
        self.debug('converted steps={}'.format(pos))

        def func():
            self.set_initial_velocity(velocity)
            self.set_acceleration(acceleration)
            self.set_deceleration(deceleration)

            cmd = 'MR' if relative else 'MA'
            self.tell('{} {}'.format(cmd, pos))
            self._block()

        if block:
            func()
            return True
        else:
            t = Thread(target=func)
            t.setDaemon(True)
            t.start()
            return True
开发者ID:NMGRL,项目名称:pychron,代码行数:31,代码来源:base.py

示例13: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
def run(**kwargs):

    thread_queue = []
    for provider in list_providers("openstack"):
        mgmt_sys = cfme_data['management_systems'][provider]
        rhos_credentials = credentials[mgmt_sys['credentials']]
        default_host_creds = credentials['host_default']

        username = rhos_credentials['username']
        password = rhos_credentials['password']
        auth_url = mgmt_sys['auth_url']
        rhosip = mgmt_sys['ipaddress']
        sshname = default_host_creds['username']
        sshpass = default_host_creds['password']
        if not net.is_pingable(rhosip):
            continue
        if not net.net_check(ports.SSH, rhosip):
            print("SSH connection to {}:{} failed, port unavailable".format(
                provider, ports.SSH))
            continue
        thread = Thread(target=upload_template,
                        args=(rhosip, sshname, sshpass, username, password, auth_url, provider,
                              kwargs.get('image_url'), kwargs.get('template_name')))
        thread.daemon = True
        thread_queue.append(thread)
        thread.start()

    for thread in thread_queue:
        thread.join()
开发者ID:prachiyadav,项目名称:cfme_tests,代码行数:31,代码来源:template_upload_rhos.py

示例14: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
class Pulse:
    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret, geotags):
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.access_token = access_token
        self.access_token_secret = access_token_secret
        self.geotags = geotags
    def start(self):
        self.queue = PriorityQueue()
        self.consumer = Thread(target = consume, args = (self.queue, ))
        self.consumer.start()
        self.operater = Thread(target = operate, args = (self.queue, ))
        self.operater.start()
        self.canary = canary.Canary(self.consumer_key, self.consumer_secret,\
                                    self.access_token, self.access_token_secret)
        self.canary.queue = self.queue
        def onData(canary, data):
            try:
                timestamp = time.time()
                twit = json.loads(data)
                if 'coordinates' not in twit or not twit['coordinates']:
                    return
                try:
                    tweet = {}
                    tweet['timestamp'] = timestamp
                    tweet['text'] = twit['text']
                    tweet['id'] = str(twit['id'])#does this actually work? must test!
                    tweet['latlong'] = twit['coordinates']['coordinates'][::-1]#twitter returns these flipped
                    self.canary.queue.put((0-timestamp, tweet))
                except Exception,e:
                    traceback.print_exc()
            except Exception,e:
                traceback.print_exc()
        self.canary.onData = onData
        self.canary.startStream(self.geotags)#may not work???
开发者ID:relh,项目名称:cath-hacks,代码行数:37,代码来源:pulse.py

示例15: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import start [as 别名]
class NonBlockingStreamReader:
    def __init__(self, stream):
        '''
        stream: the stream to read from.
                Usually a process' stdout or stderr.
        '''

        self._s = stream
        self._q = Queue()

        def _populateQueue(stream, queue):
            '''
            Collect lines from 'stream' and put them in 'quque'.
            '''

            while True:
                line = stream.readline()
                if line:
                    queue.put(line)
                else:
                    break

        self._t = Thread(target = _populateQueue,
                         args = (self._s, self._q))
        self._t.daemon = True
        self._t.start() #start collecting lines from the stream

    def readline(self, timeout = None):
        try:
            return self._q.get(block = timeout is not None,
                               timeout = timeout)
        except Empty:
            return None
开发者ID:jaxon1,项目名称:dronekit-sitl,代码行数:35,代码来源:__init__.py


注:本文中的threading.Thread.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。