【问题标题】:How to execute a function call in asyncio python如何在 asyncio python 中执行函数调用
【发布时间】:2017-04-04 14:44:38
【问题描述】:

我正在尝试通过 asyncio 调用一些函数。我正在关注http://www.giantflyingsaucer.com/blog/?p=5557 这个教程。没有讲如何调用其他函数。

import asyncio


    def print_myname():
        return ("My name is xyz")

    def print_myage():
        return ("My age is 21")


    @asyncio.coroutine
    def my_coroutine(future, task_name, function_call):
        print("Task name", task_name)
        data = yield from function_call
        #yield from asyncio.get_function_source(function_call)  #I was trying this too
        future.set_result(data)


    def got_result(future):
        return future.result()


    loop = asyncio.get_event_loop()
    future1 = asyncio.Future()
    future2 = asyncio.Future()

    tasks = [
        my_coroutine(future1, 'name', print_myname()),
        my_coroutine(future2, 'age', print_myage())]

    name = future1.add_done_callback(got_result)
    age = future2.add_done_callback(got_result)

    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

    print ("name output", name)
    print ("age output", age)

它会引发无法产生的运行时错误。

Task exception was never retrieved

    future: <Task finished coro=<my_coroutine() done, defined at /home/user/Desktop/testproject/source//weather/async_t.py:11> exception=RuntimeError("Task got bad yield: 'M'",)>
    Traceback (most recent call last):
        result = coro.throw(exc)
      File "/home/user/Desktop/testproject/source/weather/async_t.py", line 14, in my_coroutine
        data = yield from function_call
    RuntimeError: Task got bad yield: 'M'

通过异常似乎已经到函数了,但是无法执行代码。

【问题讨论】:

  • 你需要括号。 yield from function_call()
  • 还是不行。我把函数改成了协程

标签: python python-asyncio coroutine function-call


【解决方案1】:

要调用常规函数,只需调用它即可。您不能 yield from 常规函数 - 仅来自协程。

代替:

data = yield from foo()

只需使用:

data = foo()

【讨论】:

  • 对,我将我的函数更改为协同例程并且它起作用了。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
相关资源
最近更新 更多