2017-04-04 62 views
0

我想通過asyncio調用一些函數。我正在關注本教程的http://www.giantflyingsaucer.com/blog/?p=5557。它不會談論如何調用其他函數。如何在asyncio中執行函數調用python

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' 

通過例外,它似乎已經去了功能,但無法執行代碼。

+0

你需要括號。 '來自function_call()產出' – dirn

+0

它仍然沒有工作。我將這些功能修改爲聯合程序 – Devyani

回答

1

要調用常規函數,只需調用它。你不能僅僅從協同程序中獲得一個正常的函數yield from

相反的:

data = yield from foo() 

只需使用:

data = foo() 
+0

對,我將我的功能改爲聯合程序並且工作。謝謝 – Devyani

相關問題