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


Python asyncio.run方法代码示例

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


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

示例1: test_roles_command_command

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_roles_command_command(self):
        """Test if the `role_info` command correctly returns the `moderator_role`."""
        self.ctx.guild.roles.append(self.moderator_role)

        self.cog.roles_info.can_run = unittest.mock.AsyncMock()
        self.cog.roles_info.can_run.return_value = True

        coroutine = self.cog.roles_info.callback(self.cog, self.ctx)

        self.assertIsNone(asyncio.run(coroutine))
        self.ctx.send.assert_called_once()

        _, kwargs = self.ctx.send.call_args
        embed = kwargs.pop('embed')

        self.assertEqual(embed.title, "Role information (Total 1 role)")
        self.assertEqual(embed.colour, discord.Colour.blurple())
        self.assertEqual(embed.description, f"\n`{self.moderator_role.id}` - {self.moderator_role.mention}\n") 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:test_information.py

示例2: test_user_command_helper_method_get_requests

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_user_command_helper_method_get_requests(self):
        """The helper methods should form the correct get requests."""
        test_values = (
            {
                "helper_method": self.cog.basic_user_infraction_counts,
                "expected_args": ("bot/infractions", {'hidden': 'False', 'user__id': str(self.member.id)}),
            },
            {
                "helper_method": self.cog.expanded_user_infraction_counts,
                "expected_args": ("bot/infractions", {'user__id': str(self.member.id)}),
            },
            {
                "helper_method": self.cog.user_nomination_counts,
                "expected_args": ("bot/nominations", {'user__id': str(self.member.id)}),
            },
        )

        for test_value in test_values:
            helper_method = test_value["helper_method"]
            endpoint, params = test_value["expected_args"]

            with self.subTest(method=helper_method, endpoint=endpoint, params=params):
                asyncio.run(helper_method(self.member))
                self.bot.api_client.get.assert_called_once_with(endpoint, params=params)
                self.bot.api_client.get.reset_mock() 
开发者ID:python-discord,项目名称:bot,代码行数:27,代码来源:test_information.py

示例3: test_fetch_webhook_logs_when_unable_to_fetch_webhook

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_fetch_webhook_logs_when_unable_to_fetch_webhook(self):
        """The `fetch_webhook` method should log an exception when it fails to fetch the webhook."""
        self.bot.fetch_webhook.side_effect = discord.HTTPException(response=MagicMock(), message="Not found.")
        self.cog.webhook_id = 1

        log = logging.getLogger('bot.cogs.duck_pond')
        with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher:
            asyncio.run(self.cog.fetch_webhook())

        self.bot.wait_until_guild_available.assert_called_once()
        self.bot.fetch_webhook.assert_called_once_with(1)

        self.assertEqual(len(log_watcher.records), 1)

        record = log_watcher.records[0]
        self.assertEqual(record.levelno, logging.ERROR) 
开发者ID:python-discord,项目名称:bot,代码行数:18,代码来源:test_duck_pond.py

示例4: test_send_webhook_correctly_passes_on_arguments

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_send_webhook_correctly_passes_on_arguments(self):
        """The `send_webhook` method should pass the arguments to the webhook correctly."""
        self.cog.webhook = helpers.MockAsyncWebhook()

        content = "fake content"
        username = "fake username"
        avatar_url = "fake avatar_url"
        embed = "fake embed"

        asyncio.run(self.cog.send_webhook(content, username, avatar_url, embed))

        self.cog.webhook.send.assert_called_once_with(
            content=content,
            username=username,
            avatar_url=avatar_url,
            embed=embed
        ) 
开发者ID:python-discord,项目名称:bot,代码行数:19,代码来源:test_duck_pond.py

示例5: test_on_raw_reaction_add_returns_on_message_with_green_checkmark_placed_by_bot

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_on_raw_reaction_add_returns_on_message_with_green_checkmark_placed_by_bot(self, count_ducks, is_staff):
        """The `on_raw_reaction_add` event should return when the message has a green check mark placed by the bot."""
        channel_id = 31415926535
        message_id = 27182818284
        user_id = 16180339887

        channel, message, member, payload = self._raw_reaction_mocks(channel_id, message_id, user_id)

        payload.emoji = helpers.MockPartialEmoji(name=self.unicode_duck_emoji)
        payload.emoji.is_custom_emoji.return_value = False

        message.reactions = [helpers.MockReaction(emoji=self.checkmark_emoji, users=[self.bot.user])]

        is_staff.return_value = True
        count_ducks.side_effect = AssertionError("Expected method to return before calling `self.count_ducks`")

        self.assertIsNone(asyncio.run(self.cog.on_raw_reaction_add(payload)))

        # Assert that we've made it past `self.is_staff`
        is_staff.assert_called_once() 
开发者ID:python-discord,项目名称:bot,代码行数:22,代码来源:test_duck_pond.py

示例6: get

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def get(cli_ctx, key, prefix, scope):
    '''
    Get the value of a key in the configured etcd namespace.
    '''
    async def _impl():
        async with etcd_ctx(cli_ctx) as etcd:
            try:
                if prefix:
                    data = await etcd.get_prefix(key, scope=scope)
                    print(json.dumps(dict(data), indent=4))
                else:
                    val = await etcd.get(key, scope=scope)
                    if val is None:
                        sys.exit(1)
                    print(val)
            except Exception:
                log.exception('An error occurred.')
    with cli_ctx.logger:
        asyncio.run(_impl()) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:etcd.py

示例7: emulate

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def emulate(self, *coroutines: Iterable[asyncio.coroutine]):
        """ Convenience method that runs a full method in a blocking manner.
        Performs connect, run, and then disconnect.

        Parameters:
            *coroutines -- any asyncio coroutines to be executed concurrently
                           with our emulation
        """

        self.connect()

        try:
            self.run_with(*coroutines)
        except KeyboardInterrupt:
            pass
        finally:
            self.disconnect()


    #
    # I/O interface.
    # 
开发者ID:usb-tools,项目名称:Facedancer,代码行数:24,代码来源:device.py

示例8: run

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def run():
    mdb = None
    if 'test' in sys.argv:
        import credentials

        mdb = motor.motor_asyncio.AsyncIOMotorClient(credentials.test_mongo_url).avrae
    else:
        mclient = motor.motor_asyncio.AsyncIOMotorClient(os.getenv('MONGO_URL', "mongodb://localhost:27017"))
        mdb = mclient[os.getenv('MONGO_DB', "avrae")]

    if 'bestiary' in sys.argv:
        input(f"Reindexing {mdb.name} bestiaries. Press enter to continue.")
        await migrate_bestiaries(mdb)

    if 'tome' in sys.argv:
        input(f"Reindexing {mdb.name} tomes. Press enter to continue.")
        await migrate_tomes(mdb)

    if 'pack' in sys.argv:
        input(f"Reindexing {mdb.name} packs. Press enter to continue.")
        await migrate_packs(mdb) 
开发者ID:avrae,项目名称:avrae,代码行数:23,代码来源:hb_sub_reindexing.py

示例9: test_async_this_thread

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def test_async_this_thread(server):
    async def _():
        loop = asyncio.get_event_loop()
        fs = fsspec.filesystem("http", asynchronous=True, loop=loop)

        with pytest.raises(RuntimeError):
            # fails because client creation has not yet been awaited
            await fs._cat(server + "/index/realfile")

        await fs.set_session()  # creates client

        out = await fs._cat(server + "/index/realfile")
        del fs
        assert out == data

    asyncio.run(_()) 
开发者ID:intake,项目名称:filesystem_spec,代码行数:18,代码来源:test_http.py

示例10: _patch_asyncio

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def _patch_asyncio():
    """
    Patch asyncio module to use pure Python tasks and futures,
    use module level _current_tasks, all_tasks and patch run method.
    """
    def run(future, *, debug=False):
        loop = asyncio.get_event_loop()
        loop.set_debug(debug)
        return loop.run_until_complete(future)

    if sys.version_info >= (3, 6, 0):
        asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
            asyncio.tasks._PyTask
        asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
            asyncio.futures._PyFuture
    if sys.version_info < (3, 7, 0):
        asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks  # noqa
        asyncio.all_tasks = asyncio.tasks.Task.all_tasks  # noqa
    if not hasattr(asyncio, '_run_orig'):
        asyncio._run_orig = getattr(asyncio, 'run', None)
        asyncio.run = run 
开发者ID:erdewit,项目名称:nest_asyncio,代码行数:23,代码来源:nest_asyncio.py

示例11: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGT for the sepcified user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string. ')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
开发者ID:skelsec,项目名称:minikerberos,代码行数:19,代码来源:getTGT.py

示例12: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Gets an S4U2proxy ticket impersonating given user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('targetuser', help='')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logger.setLevel(logging.WARNING)
	elif args.verbose == 1:
		logger.setLevel(logging.INFO)
	else:
		logger.setLevel(1)

	asyncio.run(amain(args)) 
开发者ID:skelsec,项目名称:minikerberos,代码行数:21,代码来源:getS4U2proxy.py

示例13: main

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGS for the sepcified user and specified service', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_string', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-u', action='store_true', help='Use UDP instead of TCP (not tested)')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
开发者ID:skelsec,项目名称:minikerberos,代码行数:21,代码来源:getTGS.py

示例14: run

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def run(self):
		req = self.construct_tgt_req()

		rep = await self.ksoc.sendrecv(req.dump(), throw = False)

		if rep.name != 'KRB_ERROR':	
			# user doesnt need preauth, but it exists
			return True
			
		elif rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:
			# any other error means user doesnt exist
			return False
			
		else:
			# preauth needed, only if user exists
			return True 
开发者ID:skelsec,项目名称:minikerberos,代码行数:18,代码来源:security.py

示例15: run_cli

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run [as 别名]
def run_cli(self, *args, input: Optional[str]=None):
        conn_args = self.get_connect_args()

        cmd_args = (
            '--host', conn_args['host'],
            '--port', str(conn_args['port']),
            '--user', conn_args['user'],
        ) + args

        if conn_args['password']:
            cmd_args = ('--password-from-stdin',) + cmd_args
            if input is not None:
                input = f"{conn_args['password']}\n{input}"
            else:
                input = f"{conn_args['password']}\n"

        subprocess.run(
            ('edgedb',) + cmd_args,
            input=input.encode() if input else None,
            check=True,
            capture_output=True,
        ) 
开发者ID:edgedb,项目名称:edgedb,代码行数:24,代码来源:server.py


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