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


Python Thread.setDaemon方法代码示例

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


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

示例1: main

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

    # Configure the example
    opt_parser = optparse.OptionParser()
    opt_parser.add_option("-s", "--source", dest="source", default="stdin", help="Where to read the events from. \
        Can be 'local' (simulates an embedded driver), \
        'http' (listening to XML events submitted by HTTP POST) or \
        'stdin' (reading events on the standard output, separated by an empty line). Defaults to 'stdin'")
    opt_parser.add_option("-p", "--port", dest="port", default="8080",
        help="If source is HTTP, listen on this port for HTTP POST events. Defaults to 8080")
    (options, args) = opt_parser.parse_args()

    # Start the logger thread
    logger_thread = Thread(target=logger_loop)
    logger_thread.setDaemon(True)
    logger_thread.start()

    # Start the chosen listener
    if options.source == 'http':
        listen_http(int(options.port))

    if options.source == 'stdin':
        listen_stdin()

    if options.source == 'local':
        listen_local()

    # Wait
    logger_thread.join()
开发者ID:gmassei,项目名称:wfrog,代码行数:31,代码来源:xmlstream.py

示例2: send_async

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [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

示例3: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
    def __init__(self, tname, task_queue, flt, suc, fail, headers={}, proxy=None, proxy_policy=None,
            retry=3, timeout=10, logger=None, keep_alive=None, stream_mode=False):
        """
        Construct a new 'HttpWorker' obkect

        :param tname: The name of this http worker
        :param task_queue: The task Queue instance
        :param flt: the filter function
        :param suc: the function to call when succeeded
        :param fail: the function to call when failed
        :param headers: custom HTTP headers
        :param proxy: proxy dict
        :param proxy_policy: a function to determine whether proxy should be used
        :param retry: retry count
        :param timeout: timeout in seconds
        :param logger: the Logger instance
        :param keep_alive: the callback to send keep alive
        :param stream_mode: set the request to use stream mode, keep_alive will be called every iteration
        :return: returns nothing
        """
        HttpReq.__init__(self, headers, proxy, proxy_policy, retry, timeout, logger, tname = tname)
        Thread.__init__(self, name = tname)
        Thread.setDaemon(self, True)
        self.task_queue = task_queue
        self.logger = logger
        self._keepalive = keep_alive
        self._exit = lambda x: False
        self.flt = flt
        self.f_suc = suc
        self.f_fail = fail
        self.stream_mode = stream_mode
        # if we don't checkin in this zombie_threshold time, monitor will regard us as zombie
        self.zombie_threshold = timeout * (retry + 1) 
        self.run_once = False
开发者ID:fffonion,项目名称:xeHentai,代码行数:36,代码来源:worker.py

示例4: do_main_program

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [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

示例5: TestStatsdLoggingDelegation

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
class TestStatsdLoggingDelegation(unittest.TestCase):
    def setUp(self):
        self.port = 9177
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(('localhost', self.port))
        self.queue = Queue()
        self.reader_thread = Thread(target=self.statsd_reader)
        self.reader_thread.setDaemon(1)
        self.reader_thread.start()

    def tearDown(self):
        # The "no-op when disabled" test doesn't set up a real logger, so
        # create one here so we can tell the reader thread to stop.
        if not getattr(self, 'logger', None):
            self.logger = utils.get_logger({
                'log_statsd_host': 'localhost',
                'log_statsd_port': str(self.port),
            }, 'some-name')
        self.logger.increment('STOP')
        self.reader_thread.join(timeout=4)
        self.sock.close()
        del self.logger
        time.sleep(0.15)  # avoid occasional "Address already in use"?

    def statsd_reader(self):
        while True:
            try:
                payload = self.sock.recv(4096)
                if payload and 'STOP' in payload:
                    return 42
                self.queue.put(payload)
            except Exception, e:
                sys.stderr.write('statsd_reader thread: %r' % (e,))
                break
开发者ID:AsylumCorp,项目名称:swift,代码行数:36,代码来源:test_utils.py

示例6: main

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
 def main(self):
     global QUEUE
     QUEUE = TaskQueue(self.config)
     
     indexers = self.buildIndexers()
            
     for indexer in indexers: 
         QUEUE.put(indexer)
     
     #start stat printing
     if self.statManager != None:
         timer = Timer()
         timer.scheduleAtFixedRate(StatLoggerTask(self.statManager, indexers), 0, self.config.statLoggingFrequency*60*1000)
     
     #start worker threads        
     workers = []
     for i in range(self.config.numThreads):
         t = Thread (target=ISWorker(self.config, self.statManager))
         workers.append(t)
         t.setDaemon(1)
         t.start()
             
     for t in workers:
         t.join()
         
     log('Done!')
开发者ID:piyush76,项目名称:EMS,代码行数:28,代码来源:isctrl.py

示例7: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
    def run(self):
        '''
        Does the job
        '''
        self.parser.add_option("-l", "--list", default=False, action="store_true", 
            help = "If present, list hosts configured in site.xml")
        self.parser.add_option("-a", "--artm", default=False, action="store_true", 
            help = "If present, include lo-art-1 to cycle/off")
        self.parser.add_option("-c", "--cob", default=False, action="store_true", 
            help = "If present, reboot only cob-* machines. cob-dmc is not rebooted because it belong to CONTROL subsystem.")
        self.parser.add_option("-o", "--off", default=False, action="store_true", 
            help = "If present, turn off the machines instead cycle them.")
        self.parser.add_option("-t", "--timeout", default=150, 
            help = "Set timeout to wait the recovered hosts. Default is 150 secs")
        self.parse()
        self.parse_args()
        self.get_hosts()
        if self.list is False:
            lastpdu = 'none'
            for host in self.hosts:
                currentpdu = str(self.get_pdu(host)[0])
                if currentpdu != lastpdu:
                    lastpdu = currentpdu
                    self.pstrip_cmd(self.get_pdu(host))
                    time.sleep(1)
                else:
                    time.sleep(2)
                    lastpdu = currentpdu
                    self.pstrip_cmd(self.get_pdu(host))
            if self.verbose:
                print self._get_time()+" Waiting for hosts ..."
            if self.off is False:
                queue = Queue()
                for host in self.hosts:
                    queue.put(host)
                    self.remaining_hosts.append(host)
                for host in self.hosts:
                    rh =  Thread(target=self.recover_host,args=(host, self.timeout,queue))
                    rh.setDaemon(True)
                    rh.start()
                queue.all_tasks_done.acquire()
                try:
                    endtime = time.time() + self.timeout
                    while queue.unfinished_tasks:
                        remaining = endtime -  time.time()
                        if remaining <= 0.0:
                            raise timeOut('Time Out Raise!!!')
                        queue.all_tasks_done.wait(remaining)
                except timeOut:
                    print "%s Probably %d hosts are still rebooting, please check ..." % (self._get_time(), int(queue.unfinished_tasks))
                    print "%s Please check these hosts:" % self._get_time()
                    for h in self.remaining_hosts:
                        print "%s ---> \033[31m%s\033[0m" % (self._get_time(), h)
                finally:
                    queue.all_tasks_done.release()

        else:
            print "Hosts configured in site.xml"
            for host in self.hosts:
                print host
开发者ID:normansaez,项目名称:scripts,代码行数:62,代码来源:nukeDiskless.py

示例8: setWorkers

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
def setWorkers():
    for i in range(num_threads):
        worker = Thread(target=threadFunc, args=(i,queue))
        # needs to be daemon threads, otherwise main program will not exit
        # after queue.join. 
        worker.setDaemon(True)
        worker.start()
开发者ID:possientis,项目名称:Prog,代码行数:9,代码来源:thread_dispatch.py

示例9: fetchDatas

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
 def fetchDatas(self, flow, step=0, *args, **kwargs):
     try:
         start = time.time()
         self.fire(flow, step, *args, **kwargs)
         if self.timeout > -1:
             def check(self, timeout):
                 time.sleep(timeout)
                 self.exit()
                 print 'Time out of %s. ' % str(self.timeout)
             watcher = Thread(
                 target=check, args=(self, self.timeout - (time.time() - start)))
             watcher.setDaemon(True)
             watcher.start()
         self.waitComplete()
         it = self.tinder(flow)
         while True:
             if hasattr(it, 'store'):
                 try:
                     it.store(None, forcexe=True)
                 except:
                     t, v, b = sys.exc_info()
                     err_messages = traceback.format_exception(t, v, b)
                     print(': %s, %s \n' % (str(args), str(kwargs)),
                           ','.join(err_messages), '\n')
             if hasattr(it, 'next'):
                 it = it.next
             else:
                 break
         self.dones.add(flow)
         end = time.time()
         self.totaltime = end - start
         return True
     except:
         return False
开发者ID:spawn3,项目名称:python-util,代码行数:36,代码来源:spider.py

示例10: put_fb_page

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
def put_fb_page(fb_user_obj, brand_name, page_obj):
    url = "%s" % (page_obj["id"])
    page_data = GraphAPI(page_obj["access_token"]).request(url)

    fb_page = FBPage()
    fb_page.page_id = page_data["id"]
    fb_page.name = page_data["name"]
    page_data.pop("id", None)
    page_data.pop("name", None)
    fb_page.fields = page_data

    def save_obj(page):
        return FBPage.collection().save(page.serialize())

    dupe_obj = FBPage.collection().find_one({"page_id": page_obj["id"]})
    if dupe_obj is None:
        fb_page._id = save_obj(fb_page)
    else:
        FBPage.collection().update({"page_id": page_obj["id"]}, fb_page.serialize())
        fb_page = FBPage.unserialize(FBPage.collection().find_one({"page_id": page_obj["id"]}))

    update_brand_mapping(fb_user_obj.u_id, brand_name, "facebook", page_obj["id"], page_obj["access_token"])

    t = Thread(target=load_fb_page_to_db, args=(page_obj["id"], page_obj["access_token"]))
    t.setDaemon(False)
    t.start()

    return fb_page
开发者ID:nubela,项目名称:unifide-backend,代码行数:30,代码来源:action.py

示例11: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
 def __init__(self):
     self.for_upload = []
     self.url_stats = {}
     self.tempdir = 'tmp'
     self.current_date = datetime.datetime.today().strftime("%Y-%m-%d")
     self.create_temp_dir()
     self.get_image_data()
     for chunk in self.chunks(glob.glob1(self.tempdir, "*.jpg"), 50):
         worker = Thread(target=self.create_thumbnail, args=(chunk,))
         worker.setDaemon(True)
         worker.start()
     while (activeCount() > 1):
         time.sleep(5)
     s3key = 'AKIAIYZERMTB6Z5NPF5Q'
     s3secret = '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'
     bucket_name = "hrachya-test"
     self.s3_conn = boto.connect_s3(s3key, s3secret)
     self.bucket_obj = self.s3_conn.get_bucket(bucket_name)
     for chunk in self.chunks(glob.glob1(self.tempdir, "*.jpg"), 100):
         worker = Thread(target=self.aws_s3_uploader, args=(chunk,))
         worker.setDaemon(True)
         worker.start()
     while (activeCount() > 1):
         time.sleep(5)
     #self.aws_s3_uploader()
     self.update_record()
     self.cleaner()
开发者ID:akalex,项目名称:DevProject,代码行数:29,代码来源:image_parser.py

示例12: main

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
def main():
    global ws
    global loop
    ws = WebsocketClient()
    tts.init(ws)
    ConfigurationManager.init(ws)
    loop = RecognizerLoop()
    loop.on('recognizer_loop:utterance', handle_utterance)
    loop.on('recognizer_loop:record_begin', handle_record_begin)
    loop.on('recognizer_loop:wakeword', handle_wakeword)
    loop.on('recognizer_loop:record_end', handle_record_end)
    loop.on('speak', handle_speak)
    ws.on('open', handle_open)
    ws.on('speak', handle_speak)
    ws.on(
        'multi_utterance_intent_failure',
        handle_multi_utterance_intent_failure)
    ws.on('recognizer_loop:sleep', handle_sleep)
    ws.on('recognizer_loop:wake_up', handle_wake_up)
    ws.on('mycroft.stop', handle_stop)
    ws.on("mycroft.paired", handle_paired)
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()

    try:
        loop.run()
    except KeyboardInterrupt, e:
        logger.exception(e)
        event_thread.exit()
        sys.exit()
开发者ID:forslund,项目名称:mycroft-core,代码行数:33,代码来源:main.py

示例13: start_model_pulling_in_worker

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
def start_model_pulling_in_worker(model_server: Optional[EndpointConfig],
                                  wait_time_between_pulls: int,
                                  project: 'Project') -> None:
    worker = Thread(target=_run_model_pulling_worker,
                    args=(model_server, wait_time_between_pulls, project))
    worker.setDaemon(True)
    worker.start()
开发者ID:marami52,项目名称:rasa_nlu,代码行数:9,代码来源:project.py

示例14: main

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
def main():
    global best
    parser = argparse.ArgumentParser(description="ping multiple hosts")
    parser.add_argument("-f", "--file", help="a file contain host list, one line one host")
    parser.add_argument("hosts", nargs="*", metavar="HOST", help="host to ping")
    args = parser.parse_args()

    if args.file is not None:
        try:
            for line in open(args.file).readlines():
                line = line.strip()
                if line == "" or line[0] == "#":
                    continue
                args.hosts.append(line)
        except IOError:
            pass

    for ip in args.hosts:
        queue.put(ip.strip())

    for i in range(num_threads):
        worker = Thread(target=ping)
        worker.setDaemon(True)
        worker.start()

    queue.join()
    print "The best host is \033[92m %s : %s" % (best['host'], best['speed'])
开发者ID:liyaodong,项目名称:testVPN,代码行数:29,代码来源:speedtest.py

示例15: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import setDaemon [as 别名]
class Worker:
    def __init__(self):
        self.q = Queue()
        self.t = Thread(target=self._handle)
        self.t.setDaemon(True)
        self.t.start()

    def _handle(self):
        while True:
            reset_caches()

            fn = self.q.get()
            try:
                fn()
                self.q.task_done()
            except:
                import traceback
                print traceback.format_exc()

    def do(self, fn, *a, **kw):
        fn1 = lambda: fn(*a, **kw)
        self.q.put(fn1)

    def join(self):
        self.q.join()
开发者ID:AbieKatz,项目名称:reddit,代码行数:27,代码来源:amqp.py


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