asyncio print something while waiting for user input - python

I have a simple script, I want the user to be able to input something whenever he wants, but I want to also print something out in the meantine, this is my code:
import asyncio
async def user_input():
while True:
content = input('> ')
async def print_something():
await asyncio.sleep(10)
print('something')
async def main():
tasks = [user_input(), print_something()]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
It lets me input, but it doesn't print something, how can I achieve that?

input is a blocking function and cannot be used with inside coroutines straightforwardly. But you could start it in a separate thread by means of run_in_executor:
import asyncio
async def user_input():
while True:
loop = asyncio.get_event_loop()
content = await loop.run_in_executor(None, input, "> ")
print(content)
async def print_something():
await asyncio.sleep(5)
print('something')
async def main():
tasks = [user_input(), print_something()]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Update: Also you can use aioconsole lib, which provides asyncio-based console functions:
from aioconsole import ainput
async def user_input():
while True:
content = await ainput(">")
print(content)

The short answer is async cannot do what you are wanting. While you did declare your functions as async the python function input is not async, it is a blocking function. So it will block the event loop and nothing else will run.
I answered a question awhile back that kinda explains how async works in python. I'll link it. But in order to do what you want you need to use threads not async.
https://stackoverflow.com/a/63237798/9270488
If you want to use threads with async then look into ThreadExecutor

Related

Running asynchronous functions in non-asynchronous functions

I'm trying to run some asynchronous functions in her asynchronous function, the problem is, how did I understand that functions don't run like that, then how do I do it? I don't want to make the maze_move function asynchronous.
async def no_stop():
#some logic
await asyncio.sleep(4)
async def stop(stop_time):
await asyncio.sleep(stop_time)
#some logic
def maze_move():
no_stop()
stop(1.5)
async def main(websocket):
global data_from_client, data_from_server, power_l, power_r
get_params()
get_data_from_server()
get_data_from_client()
while True:
msg = await websocket.recv()
allow_data(msg)
cheker(data_from_client)
data_from_server['IsBrake'] = data_from_client['IsBrake']
data_from_server['powerL'] = power_l
data_from_server['powerR'] = power_r
await websocket.send(json.dumps(data_from_server))
print(data_from_client['IsBrake'])
start_server = websockets.serve(main, 'localhost', 8080)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
How about:
def maze_move():
loop = asyncio.get_event_loop()
loop.run_until_complete(no_stop())
loop.run_until_complete(stop(1.5))
If you wanted to run two coroutines concurrently, then:
def maze_move():
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(no_stop(), stop(1.5)))
Update Based on Updated Question
I am guessing what it is you want to do (see my comment to your question):
First, you cannot call from maze_move coroutines such as stop directly since stop() does not result in calling stop it just returns a coroutine object. So maze_move has to be modified. I will assume you do not want to make it a coroutine itself (why not as long as you already have to modify it?). And further assuming you want to invoke maze_move from a coroutine that wishes to run concurrently other coroutines, then you can create a new coroutine, e.g. maze_move_runner that will run maze_move in a separate thread so that it does not block other concurrently running coroutines:
import asyncio
import concurrent.futures
async def no_stop():
#some logic
print('no stop')
await asyncio.sleep(4)
async def stop(stop_time):
await asyncio.sleep(stop_time)
print('stop')
#some logic
async def some_coroutine():
print('Enter some_coroutine')
await asyncio.sleep(2)
print('Exit some_coroutine')
return 1
def maze_move():
# In case we are being run directly and not in a separate thread:
try:
loop = asyncio.get_running_loop()
except:
# This thread has no current event loop, so:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(no_stop())
loop.run_until_complete(stop(1.5))
return 'Done!'
async def maze_move_runner():
loop = asyncio.get_running_loop()
# Run in another thread:
return await loop.run_in_executor(None, maze_move)
async def main():
loop = asyncio.get_running_loop()
results = await (asyncio.gather(some_coroutine(), maze_move_runner()))
print(results)
asyncio.run(main())
Prints:
Enter some_coroutine
no stop
Exit some_coroutine
stop
[1, 'Done!']
But this would be the most straightforward solution:
async def maze_move():
await no_stop()
await stop(1.5)
return 'Done!'
async def main():
loop = asyncio.get_running_loop()
results = await (asyncio.gather(some_coroutine(), maze_move()))
print(results)
If you have an already running event loop, you can define an async function inside of a sync function and launch it as task:
def maze_move():
async def amaze_move():
await no_stop()
await stop(1.5)
return asyncio.create_task(amaze_move())
This function returns an asyncio.Task object which can be used in an await expression, or not, depending on requirements. This way you won't have to make maze_move itself an async function, although I don't know why that would be a goal. Only a async function can run no_stop and stop, so you've got to have an async function somewhere.

run a function concurrently with client.run() in discord

so i have a discord bot and also another function that i want to run, but i want them to run concurrently but i couldn't make them run without one of them blocking the other, here's an example code
ps: disnake is a fork of dicord.py so it works the same mostly
import disnake
import time
bot = commands.Bot()
async on_message(message):
if message.content == "hello bot":
await message.channel.send("hey user")
x=0
def counting():
while True:
x += 1
print(x)
time.sleep(1)
#here is the issue mostly
bot.run(token)
counting()
i want the bot to run normally, while the other function is running and counting "1" "2" on my terminal, but i can't get to make them both work
Disnake is an async-await library, which means that you should use non-blocking functions. Moreover, the fonctions you want to make concurrent should be async and contain await suspension points in order to let other concurrent routines an opportunity to execute.
The issue is that Bot.run() is a blocking call as the documentation mentions. Moreover your counting() function is not async and does not contain any await. Thus, the two functions cannot run concurrently. Also, you should not use time.sleep() with AsyncIO as it is a blocking operation. You should use asyncio.sleep().
the program could look like this:
import asyncio
import disnake
async on_message(message):
if message.content == "hello bot":
await message.channel.send("hey user")
async def run_bot(bot: Bot, token: str):
try:
await bot.start(token)
except KeyboardInterrupt:
await bot.close()
async def count():
count = 0
while True:
await asyncio.sleep(1.0)
count += 1
print(count)
async def main():
bot = commands.Bot()
token = "<user_token>"
await asyncio.gather(
count(),
run_bot(bot, token)
)
await bot.close()
if __name__ == "__main__":
asyncio.run(main())
Note: you did not seem to use on_message() in your code, which is probably an error.

How to queue requests until the function returns a response for a previous request?

When the user sends !bot in a special channel, the code runs a function that runs for 20-30 seconds (depends on some_var). My problem is that if several people write !bot , the code will reverse this in multiple threads. How do I queue for these requests?
I tried to understand asyncio, discord.ext.tasks, but can't figure out how it works
#client.command()
async def test(ctx, *args):
data = args
if data:
answer = some_function(data[0]) #works from 5 seconds to 1 minute or more
await ctx.send(answer)
Everything works well, but I just don't want to load the system so much, I need a loop to process requests first in - first out
You can use an asyncio.Queue to queue tasks, then process them sequentially in a background loop:
import asyncio
from discord.ext import commands, tasks
queue = asyncio.Queue()
bot = commands.Bot('!')
#tasks.loop(seconds=1.0)
async def executor():
task = await queue.get()
await task
queue.task_done()
#executor.before_loop
async def before():
await bot.wait_until_ready()
#bot.command()
async def example(ctx, num: int):
await queue.put(helper(ctx, num))
async def helper(ctx, num):
await asyncio.sleep(num)
await ctx.send(num)
executor.start()
bot.run('token')
Make some_function() to async then await it. Then all test command will be processed simultaneously.
async some_function(...):
# something to do
#client.command()
async def test(ctx, *args):
if args:
answer = await some_function(data[0])
await ctx.send(answer)

Use timer decorators to trigger telethon methods

I want to make a decorator for a project of mine that every x seconds certain telethon task will be started.
I've asked in the telethon group and someone give me a small decorator but the problem here is that I need to start the loop using run_until_complete and I already use it when starting the client. Here is my code:
def periodic(period):
def scheduler(fcn):
async def wrapper():
while True:
asyncio.ensure_future(fcn())
await asyncio.sleep(period)
return wrapper
return scheduler
#periodic(2)
async def do_something():
await asyncio.sleep(5) # Do some heavy calculation
me = await client.get_me()
print(me.stingfy())
Now I already have a loop running in main:
if __name__ == "__main__":
async def start():
await client.start()
await client.get_me()
await client.run_until_disconnected()
loop = asyncio.get_event_loop()
loop.run_until_complete(start())
and I can't run another loop because if I do that it seems to close this one. Any ideas about how to make this work?
It looks like you desire to run multiple functions at same time. So you can use asyncio.Task or asyncio.create_task to create tasks and add them into list, then run them through using asyncio.wait or etc.
import asyncio
def periodic(period):
def scheduler(fcn):
async def wrapper():
while 1:
asyncio.ensure_future(fcn())
await asyncio.sleep(period)
return wrapper
return scheduler
#periodic(2)
async def do_something():
print("Im running")
async def client():
while 1:
await asyncio.sleep(1)
print("This is client")
if __name__ == "__main__":
async def start():
task = [asyncio.Task(client()),
asyncio.Task(do_something())]
done, pending = await asyncio.wait(task)
loop = asyncio.get_event_loop()
loop.run_until_complete(start())

How to make request without blocking (using asyncio)?

I would like to achieve the following using asyncio:
# Each iteration of this loop MUST last only 1 second
while True:
# Make an async request
sleep(1)
However, the only examples I've seen use some variation of
async def my_func():
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, requests.get, 'http://www.google.com')
loop = asyncio.get_event_loop()
loop.run_until_complete(my_func())
But run_until_complete is blocking! Using run_until_complete in each iteration of my while loop would cause the loop to block.
I've spent the last couple of hours trying to figure out how to correctly run a non-blocking task (defined with async def) without success. I must be missing something obvious, because something as simple as this should surely be simple. How can I achieve what I have described?
run_until_complete runs the main event loop. It's not "blocking" so to speak, it just runs the event loop until the coroutine you passed as a parameter returns. It has to hang because otherwise, the program would either stop or be blocked by the next instructions.
It's pretty hard to tell what you are willing to achieve, but this piece code actually does something:
async def my_func():
loop = asyncio.get_event_loop()
while True:
res = await loop.run_in_executor(None, requests.get, 'http://www.google.com')
print(res)
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(my_func())
It will perform a GET request on Google homepage every seconds, popping a new thread to perform each request. You can convince yourself that it's actually non-blocking by running multiple requests virtually in parallel:
async def entrypoint():
await asyncio.wait([
get('https://www.google.com'),
get('https://www.stackoverflow.com'),
])
async def get(url):
loop = asyncio.get_event_loop()
while True:
res = await loop.run_in_executor(None, requests.get, url)
print(url, res)
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(entrypoint())
Another thing to notice is that you're running requests in separate threads each time. It works, but it's sort of a hack. You should rather be using a real asynchronus HTTP client such as aiohttp.
This is Python 3.10
asyncio is single threaded execution, using await to yield the cpu to other function until what is await'ed is done.
import asyncio
async def my_func(t):
print("Start my_func")
await asyncio.sleep(t) # The await yields cpu, while we wait
print("Exit my_func")
async def main():
asyncio.ensure_future(my_func(10)) # Schedules on event loop, we might want to save the returned future to later check for completion.
print("Start main")
await asyncio.sleep(1) # The await yields cpu, giving my_func chance to start.
print("running other stuff")
await asyncio.sleep(15)
print("Exit main")
if __name__ == "__main__":
asyncio.run(main()) # Starts event loop

Categories

Resources