Как вернуть значение из функции asyn c - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть функция asyn c, от которой я пытаюсь получить возвращаемую переменную, но я не могу заставить ее работать по какой-то причине, я пробовал несколько разных вещей из поиска в Google, но они все возвращая похожую ошибку.

У меня есть эта функция:

@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, чтобы увидеть, могу ли я видеть, что происходит, и отдых это ошибка. Кажется, он не возвращает никакого значения, а только саму подпрограмму?

Я пытался изменить способ ссылки на функцию: x = start (ctx), x = start (), x = start et c.

Что-то я не так делаю? Как я могу вернуть переменную.

1 Ответ

0 голосов
/ 24 апреля 2020

Вам нужно await сопрограмм; т.е. x = await start(ctx)

...