简体   繁体   中英

Unable to schedule anything in asyncio. (Python 3.7.x)

I am currently working on asyncio with python 3.7.x not sure about the exact version, right now I am trying to schedule a task. And I am unable to get an output, even when running the thing forever. Here is the code I currently have

import asyncio

async def print_now():
  print("Hi there")

loop = asyncio.get_event_loop()
loop.call_later(print_now())
loop.run_until_complete(asyncio.sleep(1))

This gives the following error:

Traceback (most recent call last):
  File "D:\Coding\python\async\main.py", line 7, in <module>
    loop.call_later(print_now())
TypeError: call_later() missing 1 required positional argument: 'callback'

The call back in call_later() is print_now I've tried just print_now and print_now() I have also tried using loop.run_forever() instead of loop.run_until_complete() and so far I didn't get anything

Sometimes I get either no output or a different error.

First, yes, you're missing a delay argument . First one is supposed to be the delay while the second one is a callback ( docs ).

loop.call_later(delay, callback, *args, context=None)

Second, the callback is supposed to be a function. What you're passing is print_now() which is gonna evaluate to None . You might find out that

'NoneType' object is not callable

So you're gonna need to pass print_now — without parentheses — as a callback. This way you're passing a function instead of the result of its application.


Third, async functions are supposed to be await ed on. Your scenario doesn't seem to need that, so just drop the async keyword.

When you call an awaitable function, you create a new coroutine object. The code inside the function won't run until you then await on the function or run it as a task

From this post . You might want to check out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM