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


Python asyncio.get_event_loop方法代码示例

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


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

示例1: subscribe

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def subscribe(
        self, document: DocumentNode, *args, **kwargs
    ) -> Generator[Dict, None, None]:
        """Execute a GraphQL subscription with a python generator.

        We need an async transport for this functionality.
        """

        async_generator = self.subscribe_async(document, *args, **kwargs)

        loop = asyncio.get_event_loop()

        assert not loop.is_running(), (
            "Cannot run client.subscribe if an asyncio loop is running."
            " Use subscribe_async instead."
        )

        try:
            while True:
                result = loop.run_until_complete(async_generator.__anext__())
                yield result

        except StopAsyncIteration:
            pass 
开发者ID:graphql-python,项目名称:gql,代码行数:26,代码来源:client.py

示例2: gather

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def gather(self, wnid, relative="", include_subset=False):
        loop = asyncio.get_event_loop()
        session = self.create_session(loop)
        folders = []

        f = loop.run_until_complete(self.download_images(session, wnid, relative))
        folders.append(f)

        if include_subset:
            wnids = self._get_subsets(wnid)
            path = self.file_api.join_relative(relative, f)
            downloads = asyncio.wait([self.download_images(session, wnid, path) for wnid in wnids])
            done, pending = loop.run_until_complete(downloads)
            folders += [d.result() for d in done]

        session.close()

        return folders 
开发者ID:icoxfog417,项目名称:mlimages,代码行数:20,代码来源:imagenet_api.py

示例3: test

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def test():
    class aeff(wuy.Window):
        size = (100, 100)

        def init(self):
            asyncio.get_event_loop().call_later(2, self.exit)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # the following line is needed
    # because pytest seems to execute from a different path
    # then the executable one (think freezed)
    # ex: it works without it, in a real context
    # ex: it's needed when pytest execute the test
    # IRL : it's not needed to change the path
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    wuy.PATH = os.getcwd()  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    cf = "web/aeff.html"
    if os.path.isfile(cf):
        os.unlink(cf)
    aeff()
    assert os.path.isfile(cf), "a default file can't be created !!!"
    os.unlink(cf) 
开发者ID:manatlan,项目名称:wuy,代码行数:26,代码来源:test_createDefaultHtmlFile.py

示例4: async_run

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def async_run(tasks):
    """
    run a group of tasks async
    Requires the tasks arg to be a list of functools.partial()
    """
    if not tasks:
        return

    # start a new async event loop
    loop = asyncio.get_event_loop()
    # https://github.com/python/asyncio/issues/258
    executor = concurrent.futures.ThreadPoolExecutor(5)
    loop.set_default_executor(executor)

    async_tasks = [asyncio.ensure_future(async_task(task, loop)) for task in tasks]
    # run tasks in parallel
    loop.run_until_complete(asyncio.wait(async_tasks))
    # deal with errors (exceptions, etc)
    for task in async_tasks:
        error = task.exception()
        if error is not None:
            raise error

    executor.shutdown(wait=True) 
开发者ID:deis,项目名称:controller,代码行数:26,代码来源:utils.py

示例5: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def main(_):
  urls = get_urls_for_shard_group(
      FLAGS.urls_dir, FLAGS.shard_id, FLAGS.group_id)
  tf.logging.info("Fetching %d URLs for shard %d, group %d",
                  len(urls), FLAGS.shard_id, FLAGS.group_id)

  tf.gfile.MakeDirs(FLAGS.out_dir)
  out_fname = tfrecord_fname(FLAGS.out_dir, FLAGS.shard_id)

  with utils.timing("group_fetch"):
    logging_fnames = {}
    if FLAGS.log_samples:
      logging_fnames["samples"] = os.path.join(
          FLAGS.out_dir, "samples.%d.txt" % FLAGS.shard_id)
    loop = asyncio.get_event_loop()
    num_written = loop.run_until_complete(asyncio.ensure_future(
        fetch_urls(urls,
                   out_fname,
                   logging_fnames)))

  tf.logging.info("Total URLs: %d", len(urls))
  tf.logging.info("Num written: %d", num_written)
  tf.logging.info("Coverage: %.1f", (num_written / len(urls)) * 100) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:25,代码来源:get_references_web_single_group.py

示例6: start_work

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def start_work():
    global aredis
    loop = asyncio.get_event_loop()
    aredis = await aioredis.create_redis('redis://localhost', loop=loop)

    if await aredis.get('state') == b'running':
        return "<center>Please wait for current work to finish.</center>"
    else:
        await aredis.set('state', 'ready')

    if await aredis.get('state') == b'ready':
        loop.create_task(some_work())
        body = '''
        <center>
        work started!
        </center>
        <script type="text/javascript">
            window.location = "''' + url_for('progress') + '''";
        </script>'''
        return body 
开发者ID:pgjones,项目名称:quart,代码行数:22,代码来源:progress_bar.py

示例7: sync_with_context

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def sync_with_context(future: Awaitable) -> Any:
    context = None
    if _request_ctx_stack.top is not None:
        context = _request_ctx_stack.top.copy()
    elif _websocket_ctx_stack.top is not None:
        context = _websocket_ctx_stack.top.copy()
    elif _app_ctx_stack.top is not None:
        context = _app_ctx_stack.top.copy()

    async def context_wrapper() -> Any:
        if context is not None:
            async with context:
                return await future
        else:
            return await future

    return asyncio.get_event_loop().sync_wait(context_wrapper())  # type: ignore 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:_synchronise.py

示例8: __anext__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def __anext__(self):
        loop = asyncio.get_event_loop()
        try:
            chunk = await loop.run_in_executor(
                None, _msrest_next, self.iter_content_func
            )
            if not chunk:
                raise _MsrestStopIteration()
            if self.user_callback and callable(self.user_callback):
                self.user_callback(chunk, self.response)
            return chunk
        except _MsrestStopIteration:
            self.response.close()
            raise StopAsyncIteration()
        except Exception as err:
            _LOGGER.warning("Unable to stream download: %s", err)
            self.response.close()
            raise 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:20,代码来源:async_mixin.py

示例9: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def main():
    loop = asyncio.get_event_loop()
    big_brother = None
    try:
        pid_path = os.path.join(app_dir.user_cache_dir, 'trader.pid')
        if not os.path.exists(pid_path):
            if not os.path.exists(app_dir.user_cache_dir):
                os.makedirs(app_dir.user_cache_dir)
        with open(pid_path, 'w') as pid_file:
            pid_file.write(str(os.getpid()))
        big_brother = TradeStrategy(io_loop=loop)
        print('Big Brother is watching you!')
        print('used config file:', config_file)
        print('log stored in:', app_dir.user_log_dir)
        print('pid file:', pid_path)
        loop.create_task(big_brother.install())
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    except Exception as ee:
        logger.info('发生错误: %s', repr(ee), exc_info=True)
    finally:
        big_brother and loop.run_until_complete(big_brother.uninstall())
        logger.info('程序已退出') 
开发者ID:BigBrotherTrade,项目名称:trader,代码行数:26,代码来源:main.py

示例10: fetch_bar2

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def fetch_bar2():
    day = datetime.datetime.strptime('20160114', '%Y%m%d').replace(tzinfo=pytz.FixedOffset(480))
    end = datetime.datetime.strptime('20160914', '%Y%m%d').replace(tzinfo=pytz.FixedOffset(480))
    while day <= end:
        day, trading = await is_trading_day(day)
        if trading:
            print('process ', day)
            tasks = [
                asyncio.ensure_future(update_from_shfe(day)),
                asyncio.ensure_future(update_from_dce(day)),
                asyncio.ensure_future(update_from_czce(day)),
                asyncio.ensure_future(update_from_cffex(day)),
            ]
            await asyncio.wait(tasks)
        day += datetime.timedelta(days=1)
    print('all done!')


# asyncio.get_event_loop().run_until_complete(fetch_bar2())
# create_main_all()
# fetch_from_quandl_all()
# clean_dailybar()
# load_kt_data() 
开发者ID:BigBrotherTrade,项目名称:trader,代码行数:25,代码来源:fetch_data.py

示例11: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def __init__(self, io_loop: asyncio.AbstractEventLoop = None):
        super().__init__()
        self.io_loop = io_loop or asyncio.get_event_loop()
        self.sub_client = self.io_loop.run_until_complete(
                aioredis.create_redis((config.get('REDIS', 'host', fallback='localhost'),
                                       config.getint('REDIS', 'port', fallback=6379)),
                                      db=config.getint('REDIS', 'db', fallback=1)))
        self.redis_client = redis.StrictRedis(
            host=config.get('REDIS', 'host', fallback='localhost'),
            db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
        self.initialized = False
        self.sub_tasks = list()
        self.sub_channels = list()
        self.channel_router = dict()
        self.crontab_router = defaultdict(dict)
        self.datetime = None
        self.time = None
        self.loop_time = None 
开发者ID:BigBrotherTrade,项目名称:trader,代码行数:20,代码来源:__init__.py

示例12: db_dsn_fixture

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def db_dsn_fixture(request):
    loop = asyncio.get_event_loop()

    pg_dsn = 'postgresql://postgres:postgres@postgres:5432/postgres'
    db_name = loop.run_until_complete(init_db(pg_dsn, loop=loop))

    db_dsn = 'postgresql://postgres:postgres@postgres:5432/{}'.format(db_name)
    loop.run_until_complete(setup_db(db_dsn, loop=loop))

    def fin():
        loop.run_until_complete(drop_db(pg_dsn, db_name, loop=loop))

    request.addfinalizer(fin)
    return db_dsn

# define graph 
开发者ID:vmagamedov,项目名称:hiku,代码行数:18,代码来源:test_asyncio.py

示例13: execute

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:
        """Execute the provided document AST against the configured remote server.

        This function WILL BLOCK until the result is received from the server.

        Either the transport is sync and we execute the query synchronously directly
        OR the transport is async and we execute the query in the asyncio loop
        (blocking here until answer).
        """

        if isinstance(self.transport, AsyncTransport):

            loop = asyncio.get_event_loop()

            assert not loop.is_running(), (
                "Cannot run client.execute if an asyncio loop is running."
                " Use execute_async instead."
            )

            data: Dict[Any, Any] = loop.run_until_complete(
                self.execute_async(document, *args, **kwargs)
            )

            return data

        else:  # Sync transports
            return self.execute_sync(document, *args, **kwargs) 
开发者ID:graphql-python,项目名称:gql,代码行数:29,代码来源:client.py

示例14: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def main():
  print("Creating our event loop")
  loop = asyncio.get_event_loop()
  
  loop.run_forever()
  print("Our Loop will now run forever, this will never execute") 
开发者ID:PacktPublishing,项目名称:Learning-Concurrency-in-Python,代码行数:8,代码来源:runningLoop.py

示例15: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_event_loop [as 别名]
def main():
  loop = asyncio.get_event_loop()
  loop.run_until_complete(myWork())
  loop.stop()
  print("Loop Stopped")
  loop.close()

  print(loop.is_closed()) 
开发者ID:PacktPublishing,项目名称:Learning-Concurrency-in-Python,代码行数:10,代码来源:runUntilComplete.py


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