• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python threading.Thread类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: run_windows_service

    def run_windows_service(config):
        """ Initialize the web application and run it in the background, while
            displaying a small system tray icon to interact with the it.
        """
        import webbrowser
        from winservice import SysTrayIcon

        app = WebApplication(config)
        server_thread = Thread(target=app.run_server)
        server_thread.start()

        def on_quit(systray):
            """ Callback that stops the application. """
            IOLoop.instance().stop()
            server_thread.join()

        listening_port = config['web']['port'].get(int)
        open_browser = (
            lambda x: webbrowser.open_new_tab("http://127.0.0.1:{0}"
                                              .format(listening_port)))
        menu_options = (('Open in browser', None, open_browser),)

        SysTrayIcon(
            icon=os.path.join(os.path.dirname(sys.argv[0]), 'spreads.ico'),
            hover_text="Spreads Web Service",
            menu_options=menu_options,
            on_quit=on_quit,
            default_menu_index=1,
            on_click=open_browser)
开发者ID:LabExperimental-SIUA,项目名称:spreads,代码行数:29,代码来源:app.py


示例2: __init__

 def __init__(self, req, proxy, logger, task, exit_check=None, ignored_errors=[]):
     Thread.__init__(self, name = "monitor%s" % task.guid)
     Thread.setDaemon(self, True)
     # the count of votes per error code
     self.vote_result = {}
     # the error code to be ignored
     self.vote_cleared = set().union(ignored_errors)
     self.thread_last_seen = {}
     self.dctlock = RLock()
     self.votelock = RLock()
     self.thread_ref = {}
     self.thread_zombie = set()
     # HttpReq instance
     self.req = req
     # proxy.Pool instance
     self.proxy = proxy
     self.logger = logger
     self.task = task
     self._exit = exit_check if exit_check else lambda x: False
     self._cleaning_up = False
     if os.name == "nt":
         self.set_title = lambda s:os.system("TITLE %s" % (
             s if PY3K else s.encode(CODEPAGE, 'replace')))
     elif os.name == 'posix':
         import sys
         self.set_title = lambda s:sys.stdout.write("\033]2;%s\007" % (
             s if PY3K else s.encode(CODEPAGE, 'replace')))
开发者ID:fffonion,项目名称:xeHentai,代码行数:27,代码来源:worker.py


示例3: __init__

 def __init__(self, newJobsQueue, updatedJobsQueue, boss):
     Thread.__init__(self)
     self.newJobsQueue = newJobsQueue
     self.updatedJobsQueue = updatedJobsQueue
     self.currentjobs = list()
     self.runningjobs = set()
     self.boss = boss
开发者ID:benedictpaten,项目名称:jobTree,代码行数:7,代码来源:lsf.py


示例4: __init__

 def __init__(self, interval_sec, get_connection_holders):
     Thread.__init__(self, name="Connection heartbeat")
     self._interval = interval_sec
     self._get_connection_holders = get_connection_holders
     self._shutdown_event = Event()
     self.daemon = True
     self.start()
开发者ID:sakura-sky,项目名称:python-driver,代码行数:7,代码来源:connection.py


示例5: __init__

    def __init__(self):
        self.title = self.empty_title

        # we are listening to i3 events in a separate thread
        t = Thread(target=self._loop)
        t.daemon = True
        t.start()
开发者ID:tjaartvdwalt,项目名称:py3status,代码行数:7,代码来源:window_title_async.py


示例6: run

def run(data, d=None):
	global timer
	print(data)

	if data == "ring":
		if int(d) == 1:
			if timer:
				timer.cancel()

			timer = Timer(60, genugdavon)
			timer.start()

			check = Thread(target=check_locks)
			check.start()

			putfile('/sys/class/gpio/gpio11/value', '0')

			playsound("/root/ring-bb.wav")
		else:
			playsound("/root/ring-fis.wav")
	

	if data == "open":
#		if not locked_oben:
		playsound("/root/open.wav")
	
	if data == "summ":
		if timer:
			timer.cancel()

#		if not locked_oben:
		putfile('/sys/class/gpio/gpio11/value', '1')
		playsound("/root/summ.wav")
开发者ID:Chaotikum,项目名称:klingel,代码行数:33,代码来源:klingel.py


示例7: AntiFlapping

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,代码行数:31,代码来源:switchboard.py


示例8: get_stock

    def get_stock(self):
        self.sku = self.sku_input.get().strip()
        self.client_id = self.client_id_input.get().strip()
        self.cycle = 1

        region = self.region_input.get()

        if self.refresh_var.get():
            validity = self.refresh_is_valid()
            if not validity[0]:
                self.update_status(validity[1])
                return
            else:
                amt = int(self.refresh_amt_input.get())
                dly = float(self.refresh_dly_input.get())

                if amt <= 0:
                    self.update_status('Please enter a non-zero/negative amount.')
                    return
                if dly < 0:
                    self.update_status('Please enter a non-negative delay.')
                    return
        else:
            amt = 1
            dly = 1

        thread = Thread(name=self.sku+'_'+region, target=self.check_stock, args=[region, amt, dly])
        thread.daemon = True
        thread.start()

        self.disable_submit()
开发者ID:gearbolt,项目名称:AdidasStockChecker,代码行数:31,代码来源:Main.py


示例9: __init__

    def __init__(self, log = None):
        from threading import Event

        Thread.__init__(self)

        self.__mytid = P.mytid()

        try:
            ## get process ID of parent
            self.__parent = P.parent()
        except:
            self.__parent = None

        self.__bindings = {}
        self.__stop = 0
        self.__tasks = {}

        self.setMessageLoopDelay(0.1)
        self.__loopEvent = Event()

        if log: self.__log = Logfile()
        else: self.__log = None

        ## add ping-mechanism

        self.setPingTimeout(5.)
        self.bind(MSG_PING, -1, self._ping)
开发者ID:graik,项目名称:biskit,代码行数:27,代码来源:PVMThread.py


示例10: looped

    def looped(window, *args, **kwargs):
        if hasattr(linux_native_dialog, 'native_failed'):
            import importlib
            m = importlib.import_module('calibre.gui2.qt_file_dialogs')
            qfunc = getattr(m, 'choose_' + name)
            return qfunc(window, *args, **kwargs)
        try:
            if window is None:
                return func(window, *args, **kwargs)
            ret = [None, None]
            loop = QEventLoop(window)

            def r():
                try:
                    ret[0] = func(window, *args, **kwargs)
                except:
                    ret[1] = sys.exc_info()
                    sys.exc_clear()
                while not loop.isRunning():
                    time.sleep(0.001)  # yield so that loop starts
                loop.quit()
            t = Thread(name='FileDialogHelper', target=r)
            t.daemon = True
            t.start()
            loop.exec_(QEventLoop.ExcludeUserInputEvents)
            if ret[1] is not None:
                raise ret[1][0], ret[1][1], ret[1][2]
            return ret[0]
        except Exception:
            linux_native_dialog.native_failed = True
            import traceback
            traceback.print_exc()
            return looped(window, *args, **kwargs)
开发者ID:MarioJC,项目名称:calibre,代码行数:33,代码来源:linux_file_dialogs.py


示例11: __init__

 def __init__(self, config, pipe_name=PIPE):
     """@param pipe_name: Cuckoo PIPE server name."""
     Thread.__init__(self)
     self.pipe_name = pipe_name
     self.config = config
     self.options = config.get_options()
     self.do_run = True
开发者ID:marek2003,项目名称:cuckoo-modified,代码行数:7,代码来源:analyzer.py


示例12: start

 def start(self, *args):
     """ Creates a subprocess of nping and invokes it
         with the given arguments."""
     cline = [BotConfig.NPING_PATH]
     cline = cline + args[0]
     t = Thread(target=self.__run, args=[cline])
     t.start()
开发者ID:onura,项目名称:BotSim,代码行数:7,代码来源:DDoSModule.py


示例13: __init__

 def __init__(self, stationBase):
     Thread.__init__(self)
     self.stationBase = stationBase
     self.imageVirtuelle = None
     self.anciennePosRobot = []
     self.police = cv2.FONT_HERSHEY_SIMPLEX
     self.chargerImageVirtuelle()
开发者ID:jmprovencher,项目名称:Treasure-Picker-Robot,代码行数:7,代码来源:ImageVirtuelle.py


示例14: __init__

 def __init__(self, server):
     """
     constructor
     @param      server to run
     """
     Thread.__init__(self)
     self.server = server
开发者ID:pjc42,项目名称:pyquickhelper,代码行数:7,代码来源:documentation_server.py


示例15: __init__

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,代码行数:33,代码来源:__init__.py


示例16: __init__

    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,代码行数:25,代码来源:numbalib.py


示例17: rpc_server

def rpc_server(handler, address, authkey):
    sock = Listener(address, authkey=authkey)
    while True:
        client = sock.accept()
        t = Thread(target=handler.handle_connection, args=(client,))
        t.daemon = True
        t.start()
开发者ID:Chiva-Zhao,项目名称:pproject,代码行数:7,代码来源:rmc.py


示例18: __init__

    def __init__(self, prompt="> ", stdin=None, stdout=None):
        if _debug: ConsoleCmd._debug("__init__")
        cmd.Cmd.__init__(self, stdin=stdin, stdout=stdout)
        Thread.__init__(self, name="ConsoleCmd")

        # check to see if this is running interactive
        self.interactive = sys.__stdin__.isatty()

        # save the prompt for interactive sessions, otherwise be quiet
        if self.interactive:
            self.prompt = prompt
        else:
            self.prompt = ''

        # gc counters
        self.type2count = {}
        self.type2all = {}

        # logging handlers
        self.handlers = {}

        # set a INT signal handler, ^C will only get sent to the
        # main thread and there's no way to break the readline
        # call initiated by this thread - sigh
        if hasattr(signal, 'SIGINT'):
            signal.signal(signal.SIGINT, console_interrupt)

        # start the thread
        self.start()
开发者ID:DemandLogic,项目名称:bacpypes,代码行数:29,代码来源:consolecmd.py


示例19: __init__

 def __init__(self, name, event, function, args=[], period = 5.0):
     Thread.__init__(self)
     self.name = name
     self.stopped = event
     self.period = period
     self.function = function
     self.args = args
开发者ID:Aegeaner,项目名称:ceph-dash,代码行数:7,代码来源:probe.py


示例20: __init__

 def __init__(self, port, deviceFd, deviceLock, debug = False, aexServer = None):
     '''
     Constructor
     '''
     self.running = False
     
     self.__dataQueue = Queue(0)
     
     self.__clients = []
     self.debug = debug
     
     self.__deviceFd = deviceFd
     self.deviceLock = deviceLock
     self.aexServer=aexServer
     
     self.runningTime = 0
     self.receivingTime = 0
     self.packetsReceived = 0
     self.sleepingTimes = 0
     
     ThreadingTCPServer.__init__(self, ("", port), StimNetCom, False)
     
     ThreadingTCPServer.allow_reuse_address = True
     
     self.server_bind()
     self.server_activate()
     
     Thread.__init__(self)
开发者ID:federicohyo,项目名称:mn256r1_ncs,代码行数:28,代码来源:StimServer.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python threading.Timer类代码示例发布时间:2022-05-27
下一篇:
Python threading.Semaphore类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap