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

Python process.task_id函数代码示例

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

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



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

示例1: start_game

def start_game():
    ''' Main entry point for the application '''
    cache_actions()
    sockets = netutil.bind_sockets(8888)
    #if process.task_id() == None:
    #    tornado.process.fork_processes(-1, max_restarts = 10)
    server = HTTPServer(application)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    session_manager = SessionManager.Instance()
    if process.task_id() == None:
        scoring = PeriodicCallback(scoring_round, application.settings['ticks'], io_loop = io_loop)
        session_clean_up = PeriodicCallback(session_manager.clean_up, application.settings['clean_up_timeout'], io_loop = io_loop)
        scoring.start()
        session_clean_up.start()
    try:
        for count in range(3, 0, -1):
            logging.info("The game will begin in ... %d" % (count,))
            sleep(1)
        logging.info("Good hunting!")
        io_loop.start()
    except KeyboardInterrupt:
        if process.task_id() == 0:
            print '\r[!] Shutdown Everything!'
            session_clean_up.stop()
            io_loop.stop()
开发者ID:xaelek,项目名称:RootTheBox,代码行数:26,代码来源:__init__.py


示例2: run

 def run(self):
     logger.debug("starting main loop")
     self.handler.bind(self.port, address=None, backlog=128)
     self.handler.start(self.nprocs)
     signal.signal(signal.SIGINT, self.signal_shutdown)
     signal.signal(signal.SIGTERM, self.signal_shutdown)
     IOLoop.current().handle_callback_exception(self.handle_exception)
     taskid = '0' if task_id() == None else task_id()
     logger.debug("starting task %s (pid %d)" % (taskid, os.getpid()))
     IOLoop.instance().start()
     logger.debug("stopping main loop")
开发者ID:msfrank,项目名称:terane-toolbox,代码行数:11,代码来源:server.py


示例3: main

def main():
    """ entry """
    try:
        conf = __import__('conf')
    except ImportError as e:
        app_log.critical("Unable to load site config. ({})".format(e))
        raise SystemExit()
    parse_command_line()

    if options.debug:
        app_log.setLevel(logging.DEBUG)

    if not options.debug:
        fork_processes(None)
    options.port += task_id() or 0

    if not os.path.isdir(conf.app_path):
        app_log.critical("{p} isn't accessible, maybe "
                         "create it?".format(p=conf.app_path))
        raise SystemExit()
    app_log.debug("Starting {name} on port {port}".format(name=conf.name,
                                                          port=options.port))
    # initialize the application
    tornado.httpserver.HTTPServer(Application(options,
                                              conf)).listen(options.port,
                                                            '0.0.0.0')
    ioloop = tornado.ioloop.IOLoop.instance()
    if options.debug:
        tornado.autoreload.start(ioloop)
    # enter the Tornado IO loop
    ioloop.start()
开发者ID:sarahjanesllc-labs,项目名称:brutus,代码行数:31,代码来源:cli.py


示例4: main

def main():
    options.parse_command_line()

    _port = options.options.port
    _process_num = options.options.process
    _debug_level = options.options.debug * 10

    process.fork_processes(_process_num, max_restarts=3)

    process_port = _port + process.task_id()
    process_debug = _process_num <= 1 and _debug_level < 30

    print('Service Running on %d ...' % process_port)

    app = web.Application((
        (r'/', views.base.IndexHandler),
        (r'/home', views.base.HomeHandler),
        (r'/auth/redirect', views.auth.OAuth2RedirectHandler),
        (r'/auth/revoke', views.auth.OAuth2RevokeHandler),
        (r'/auth/authorize', views.auth.OAuth2AuthorizeHandler),
        (r'/auth/info', views.auth.OAuth2InfoHandler),
        (r'/user/info', views.rest.UserInfoHandler),
        (r'/user/option', views.rest.UserOptionHandler),
        (r'/weibo/public', views.rest.WeiboPublicHandler),
        (r'/weibo/sync', views.rest.WeiboSyncHandler),
        (r'/weibo/query', views.rest.WeiboQueryHandler),
        (r'/weibo/redirect', views.rest.WeiboRedirectHandler),
        (r'/emotion/query', views.rest.EmotionQueryHandler),
    ), debug=process_debug, cookie_secret=setting.COOKIE_SECRET)
    app.listen(process_port, xheaders=True)

    loop = ioloop.IOLoop.instance()
    loop.start()
开发者ID:codeb2cc,项目名称:noweibo,代码行数:33,代码来源:main.py


示例5: _reload_on_update

def _reload_on_update(modify_times):
    global needs_to_reload
    if _reload_attempted:
        # We already tried to reload and it didn't work, so don't try again.
        return
    if process.task_id() is not None:
        # We're in a child process created by fork_processes.  If child
        # processes restarted themselves, they'd all restart and then
        # all call fork_processes again.
        return
    for module in list(sys.modules.values()):
        # Some modules play games with sys.modules (e.g. email/__init__.py
        # in the standard library), and occasionally this can cause strange
        # failures in getattr.  Just ignore anything that's not an ordinary
        # module.
        if not isinstance(module, types.ModuleType):
            continue
        path = getattr(module, "__file__", None)
        if not path:
            continue
        if path.endswith(".pyc") or path.endswith(".pyo"):
            path = path[:-1]

        result = _check_file(modify_times, module, path)
        if result is False:
            # If any files errored, we abort this attempt at reloading.
            return
        if result is True:
            # If any files had actual changes that import properly,
            # we'll plan to reload the next time we run with no files
            # erroring.
            needs_to_reload = True

    if needs_to_reload:
        _reload()
开发者ID:284928489,项目名称:zulip,代码行数:35,代码来源:autoreload.py


示例6: set_defaults

def set_defaults():
    # type: () -> None
    instance = task_id()
    if instance is None:
        instance = 0

    default_tags = {"instance": str(instance)}

    get_plugin_proxy().set_default_stats_tags(default_tags)
开发者ID:dropbox,项目名称:grouper,代码行数:9,代码来源:stats.py


示例7: tearDown

 def tearDown(self):
     if task_id() is not None:
         # We're in a child process, and probably got to this point
         # via an uncaught exception.  If we return now, both
         # processes will continue with the rest of the test suite.
         # Exit now so the parent process will restart the child
         # (since we don't have a clean way to signal failure to
         # the parent that won't restart)
         logging.error("aborting child process from tearDown")
         logging.shutdown()
         os._exit(1)
     super(ProcessTest, self).tearDown()
开发者ID:BillyWu,项目名称:tornado,代码行数:12,代码来源:process_test.py


示例8: run

    def run(self):
        if options.debug:
            app_log.setLevel(logging.DEBUG)

        if not options.debug:
            fork_processes(None)
        options.port += task_id() or 0

        app_log.debug("Starting %s on port %s" % (cfg.platform_name, options.port))
        # initialize the application
        tornado.httpserver.HTTPServer(Application(self.commons)).listen(options.port, '0.0.0.0')
        ioloop = tornado.ioloop.IOLoop.instance()
        if options.debug:
            tornado.autoreload.start(ioloop)
        # enter the Tornado IO loop
        ioloop.start()
开发者ID:battlemidget,项目名称:cage-cmf,代码行数:16,代码来源:interface.py


示例9: test_multi_process

 def test_multi_process(self):
     self.assertFalse(IOLoop.initialized())
     port = get_unused_port()
     def get_url(path):
         return "http://127.0.0.1:%d%s" % (port, path)
     sockets = bind_sockets(port, "127.0.0.1")
     # ensure that none of these processes live too long
     signal.alarm(5)  # master process
     try:
         id = fork_processes(3, max_restarts=3)
     except SystemExit, e:
         # if we exit cleanly from fork_processes, all the child processes
         # finished with status 0
         self.assertEqual(e.code, 0)
         self.assertTrue(task_id() is None)
         for sock in sockets: sock.close()
         signal.alarm(0)
         return
开发者ID:CoolCold,项目名称:tornado,代码行数:18,代码来源:process_test.py


示例10: __init__

    def __init__(self, entries, timeout, max_clients):
        assert entries

        task_id = process.task_id()

        if options.multi_processes == -1:
            process_num = 1
        elif options.multi_processes == 0:
            process_num = process.cpu_count()
        else:
            process_num = options.multi_processes

        self._io_loop = ioloop.IOLoop()
        self._client = httpclient.AsyncHTTPClient(self._io_loop, max_clients=max_clients)

        self.timeout = timeout
        self.max_clients = max_clients
        self.requests = dict([(self.get_request(e), e) for e in entries])
        self.partial_requests = self.requests.keys()[task_id::process_num]
        self.count = len(self.partial_requests)
开发者ID:WilliamRen,项目名称:tornado-benchmark,代码行数:20,代码来源:checker.py


示例11: main

def main():
    try:
        options.parse_command_line()
        port = options.options.port
        fork = options.options.fork

        setting['PROCESS'] = fork
        setting['PORT_GROUP'] = range(port, port + fork)
        process.fork_processes(fork, max_restarts=10)

        setting['PORT'] = port + process.task_id()

        app = web.Application(
            handlers=urls,
            **SETTINGS
        )

        app.listen(setting['PORT'], xheaders=True)
        loop = ioloop.IOLoop.instance()
        loop.start()
    except Exception, e:
        logger.error(traceback.format_exc(e))
开发者ID:ccxryan,项目名称:bupt-apm,代码行数:22,代码来源:start_heypj.py


示例12: _reload_on_update

def _reload_on_update(modify_times):
    if _reload_attempted:
        # We already tried to reload and it didn't work, so don't try again.
        return
    if process.task_id() is not None:
        # We're in a child process created by fork_processes.  If child
        # processes restarted themselves, they'd all restart and then
        # all call fork_processes again.
        return
    for module in sys.modules.values():
        # Some modules play games with sys.modules (e.g. email/__init__.py
        # in the standard library), and occasionally this can cause strange
        # failures in getattr.  Just ignore anything that's not an ordinary
        # module.
        if not isinstance(module, types.ModuleType): continue
        path = getattr(module, "__file__", None)
        if not path: continue
        if path.endswith(".pyc") or path.endswith(".pyo"):
            path = path[:-1]
        _check_file(modify_times, path)
    for path in _watched_files:
        _check_file(modify_times, path)
开发者ID:Akylas,项目名称:CouchPotatoServer,代码行数:22,代码来源:autoreload.py


示例13: tornado_bidder_run

def tornado_bidder_run():
    """runs httpapi bidder agent"""

    # bind tcp port to launch processes on requests
    sockets = netutil.bind_sockets(CONFIG_OBJ["Bidder"]["Port"])

    # fork working processes
    process.fork_processes(0)

    # Tornado app implementation
    app = Application([url(r"/", TornadoFixPriceBidAgentRequestHandler)])

    # start http servers and attach the web app to it
    server = httpserver.HTTPServer(app)
    server.add_sockets(sockets)

    # perform following actions only in the parent process
    process_counter = process.task_id()
    if process_counter == 0:
        # run dummy ad server
        adserver_win = Application([url(r"/", TornadoDummyRequestHandler)])
        winport = CONFIG_OBJ["Bidder"]["Win"]
        adserver_win.listen(winport)
        adserver_evt = Application([url(r"/", TornadoDummyRequestHandler)])
        evtport = CONFIG_OBJ["Bidder"]["Event"]
        adserver_evt.listen(evtport)

        # --instantiate budget pacer
        pacer = BudgetControl()
        pacer.start(CONFIG_OBJ)

        # add periodic event to call pacer
        PeriodicCallback(pacer.http_request, CONFIG_OBJ["Banker"]["Period"]).start()

    # main io loop. it will loop waiting for requests
    IOLoop.instance().start()
开发者ID:michellepan,项目名称:rtbkit,代码行数:36,代码来源:http_bid_agent_ex.py


示例14: sigterm_handler

def sigterm_handler(signum, frame):
    print >> sys.stderr, "%s: SIGTERM received. Exiting..." % \
                         task_id(process.task_id())
    sys.exit(0)
开发者ID:smugen,项目名称:epio-custom-web-process,代码行数:4,代码来源:server.py


示例15: hello

def hello():
    cid = task_id()
    cid = "#%s" % cid if cid != None else "MAIN"
    user_ip = request.environ.get("REMOTE_ADDR", "Unknown")
    print "%s: serving a request from %s" % (cid, user_ip)
    return "Hello %s! from %s" % (user_ip, cid)
开发者ID:smugen,项目名称:epio-custom-web-process,代码行数:6,代码来源:app.py


示例16: MyApp

	# state can store objects that get updated asyncronously and are needed everywhere
	shared_system_state = MyApp(config)

	# multiple request handlers, sharing the same state
	tornado_app_config = tornado.web.Application([
			( r"/some_path", MyRequestHandler, dict(config=config, state=shared_system_state) ),
		])

	# listen on the configured port, default to 8888 if not specified
	sockets = bind_sockets(config.get('port', 8888))

	# multi-process tornado. auto forks for every core you have
	fork_processes()

	# grab the task id so you can use it to refer to unique sub processes
	shared_system_state.task_id = task_id()

	# set the server's application handler
	server = HTTPServer(tornado_app_config)
	server.add_sockets(sockets)

	# create the io loop
	main_loop = tornado.ioloop.IOLoop.instance()	

	# can add multiple asyncronous periodic loops
	async_loop = tornado.ioloop.PeriodicCallback( shared_system_state.async_function,
							config.conf['async_loop_period'],
							io_loop=main_loop )

	async_loop.start()
	main_loop.start()
开发者ID:circlesandlines,项目名称:TornadoComplexTemplate,代码行数:31,代码来源:run.py


示例17: test_multi_process

    def test_multi_process(self):
        # This test doesn't work on twisted because we use the global
        # reactor and don't restore it to a sane state after the fork
        # (asyncio has the same issue, but we have a special case in
        # place for it).
        skip_if_twisted()
        with ExpectLog(gen_log, "(Starting .* processes|child .* exited|uncaught exception)"):
            sock, port = bind_unused_port()

            def get_url(path):
                return "http://127.0.0.1:%d%s" % (port, path)
            # ensure that none of these processes live too long
            signal.alarm(5)  # master process
            try:
                id = fork_processes(3, max_restarts=3)
                self.assertTrue(id is not None)
                signal.alarm(5)  # child processes
            except SystemExit as e:
                # if we exit cleanly from fork_processes, all the child processes
                # finished with status 0
                self.assertEqual(e.code, 0)
                self.assertTrue(task_id() is None)
                sock.close()
                return
            try:
                if asyncio is not None:
                    # Reset the global asyncio event loop, which was put into
                    # a broken state by the fork.
                    asyncio.set_event_loop(asyncio.new_event_loop())
                if id in (0, 1):
                    self.assertEqual(id, task_id())
                    server = HTTPServer(self.get_app())
                    server.add_sockets([sock])
                    IOLoop.current().start()
                elif id == 2:
                    self.assertEqual(id, task_id())
                    sock.close()
                    # Always use SimpleAsyncHTTPClient here; the curl
                    # version appears to get confused sometimes if the
                    # connection gets closed before it's had a chance to
                    # switch from writing mode to reading mode.
                    client = HTTPClient(SimpleAsyncHTTPClient)

                    def fetch(url, fail_ok=False):
                        try:
                            return client.fetch(get_url(url))
                        except HTTPError as e:
                            if not (fail_ok and e.code == 599):
                                raise

                    # Make two processes exit abnormally
                    fetch("/?exit=2", fail_ok=True)
                    fetch("/?exit=3", fail_ok=True)

                    # They've been restarted, so a new fetch will work
                    int(fetch("/").body)

                    # Now the same with signals
                    # Disabled because on the mac a process dying with a signal
                    # can trigger an "Application exited abnormally; send error
                    # report to Apple?" prompt.
                    # fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True)
                    # fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True)
                    # int(fetch("/").body)

                    # Now kill them normally so they won't be restarted
                    fetch("/?exit=0", fail_ok=True)
                    # One process left; watch it's pid change
                    pid = int(fetch("/").body)
                    fetch("/?exit=4", fail_ok=True)
                    pid2 = int(fetch("/").body)
                    self.assertNotEqual(pid, pid2)

                    # Kill the last one so we shut down cleanly
                    fetch("/?exit=0", fail_ok=True)

                    os._exit(0)
            except Exception:
                logging.error("exception in child process %d", id, exc_info=True)
                raise
开发者ID:conn4575,项目名称:tornado,代码行数:80,代码来源:process_test.py


示例18: test_multi_process

    def test_multi_process(self):
        self.assertFalse(IOLoop.initialized())
        port = get_unused_port()
        def get_url(path):
            return "http://127.0.0.1:%d%s" % (port, path)
        sockets = bind_sockets(port, "127.0.0.1")
        # ensure that none of these processes live too long
        signal.alarm(5)  # master process
        id = fork_processes(3, max_restarts=3)
        if id is None:
            # back in the master process; everything worked!
            self.assertTrue(task_id() is None)
            for sock in sockets: sock.close()
            signal.alarm(0)
            return
        signal.alarm(5)  # child process
        try:
            if id in (0, 1):
                signal.alarm(5)
                self.assertEqual(id, task_id())
                server = HTTPServer(self.get_app())
                server.add_sockets(sockets)
                IOLoop.instance().start()
            elif id == 2:
                signal.alarm(5)
                self.assertEqual(id, task_id())
                for sock in sockets: sock.close()
                client = HTTPClient()

                def fetch(url, fail_ok=False):
                    try:
                        return client.fetch(get_url(url))
                    except HTTPError, e:
                        if not (fail_ok and e.code == 599):
                            raise

                # Make two processes exit abnormally
                fetch("/?exit=2", fail_ok=True)
                fetch("/?exit=3", fail_ok=True)

                # They've been restarted, so a new fetch will work
                int(fetch("/").body)

                # Now the same with signals
                # Disabled because on the mac a process dying with a signal
                # can trigger an "Application exited abnormally; send error
                # report to Apple?" prompt.
                #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True)
                #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True)
                #int(fetch("/").body)

                # Now kill them normally so they won't be restarted
                fetch("/?exit=0", fail_ok=True)
                # One process left; watch it's pid change
                pid = int(fetch("/").body)
                fetch("/?exit=4", fail_ok=True)
                pid2 = int(fetch("/").body)
                self.assertNotEqual(pid, pid2)

                # Kill the last one so we shut down cleanly
                fetch("/?exit=0", fail_ok=True)

                os._exit(0)
        except Exception:
            logging.error("exception in child process %d", id, exc_info=True)
            raise
开发者ID:BillyWu,项目名称:tornado,代码行数:66,代码来源:process_test.py


示例19: handle_stream

 def handle_stream(self, stream, addr):
     self.stream = stream
     print "====== Handle new stream from ======"
     print process.task_id(), addr
     self.handle_request(stream)
开发者ID:Shouren,项目名称:snippet,代码行数:5,代码来源:tornado_serv.py


示例20: shut_down

 def shut_down(self):
     taskid = '0' if task_id() == None else task_id()
     logger.debug("stopping task %s" % taskid)
     self.handler.stop()
     IOLoop.current().stop()
开发者ID:msfrank,项目名称:terane-toolbox,代码行数:5,代码来源:server.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python process.Subprocess类代码示例发布时间:2022-05-27
下一篇:
Python process.fork_processes函数代码示例发布时间: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