python - 如何从异步函数返回值
问题描述
我有一个异步函数,我试图从中获取返回变量,但由于某种原因我无法让它工作,我尝试了一些与谷歌搜索不同的东西,但它们都返回了类似的错误。
我有这个功能:
@bot.command()
async def start(ctx):
"""starts the server"""
try:
status = server.status()
await ctx.channel.send("The server is already online!")
except:
os.chdir(".\\Minecraft")
file = subprocess.Popen("Start.bat")
await ctx.channel.send("starting the server")
starting = True
while starting == True:
time.sleep(int(delay))
with open("outfile.txt") as outfile:
for line in outfile:
if "Done" in line:
await ctx.channel.send("server has loaded")
starting = False
return file
else:
continue
我返回变量文件
但是当我尝试在另一个函数中获取变量时
@bot.command()
async def kill(ctx):
"""shuts down the server"""
x = start(ctx)
print(x)
x.terminate()
我得到错误:
<coroutine object Command.__call__ at 0x040F7B28>
Ignoring exception in command kill:
Traceback (most recent call last):
File "C:\Users\TheRi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/TheRi/OneDrive/Desktop/Python/MinecraftDiscordBot/minecraftBot.py", line 113, in kill
x.terminate()
AttributeError: 'coroutine' object has no attribute 'terminate'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\TheRi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\TheRi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\TheRi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'terminate'
C:\Users\TheRi\AppData\Local\Programs\Python\Python38-32\lib\asyncio\events.py:81: RuntimeWarning: coroutine 'Command.__call__' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
第一行似乎是我试图打印 x 的地方,看看我是否能看到发生了什么,剩下的就是错误。它似乎没有返回任何值,而只是 co 例程本身?
我尝试改变引用函数的方式,x = start(ctx),x = start(),x = start 等。
有什么我做错了吗?我怎样才能返回变量。
解决方案
你需要await
协程;IEx = await start(ctx)
推荐阅读
- sql - 使用 Hive HQL 查找一个月的最后一个星期日“日期”和“日期”
- apostrophe-cms - 如何使 Apostrophe CMS 中的表单提交无效?
- sql - 如何循环和输出原始值
- java - 如何使用 JClouds 明确指定 S3 区域?
- django-models - 如何从在 Django 模型中扩展它的模型自动创建用户
- mysql - 不同的列给出不正确的结果
- express - 无法将数据从自定义预处理程序中间件传递到 _app.js
- python - AWS CDK 日志记录 - cdk 部署后,我收到错误消息:props.destination.bind 不是函数
- azure - 如何通过 ARM 模板在 StorageAccount 中设置选定的网络
- html - HTML/CSS 需要帮助在两个元素之间创建下划线