0

I am trying to call some functions through asyncio. I was following http://www.giantflyingsaucer.com/blog/?p=5557 this tutorial. It doesn't talk about how to call other functions.

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)

It throws a runtime error that it is not able to yield.

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'

Through the exception it seems that it has gone to the function, but unable to execute the code.

2
  • You need parentheses. yield from function_call() Commented Apr 4, 2017 at 18:03
  • It still didn't work. I changed the functions to be co-routines Commented Apr 12, 2017 at 8:55

1 Answer 1

1

To call a regular function, just call it. You can not yield from a regular function - just from a coroutine.

Instead of:

data = yield from foo()

Just use:

data = foo()
Sign up to request clarification or add additional context in comments.

1 Comment

Right, I changed my functions to be co-routines and it worked. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.