7,949 questions
0
votes
1
answer
22
views
FastAPI: Not able to use AsyncMock in "async with connection.execute()" context for aiosqlite (async sqlite3 library) while testing the endpoint
I am using Python 3.13.2
I have async with connection.execute(query) as cursor: block in my endpoint which I want to mock (connection is an object generated by await aiosqlite.connection(':memory:').
...
0
votes
0
answers
29
views
How can i stop debug output of asyncserialserver?
I run StartAsyncSerialServer from pymodbus and get a lot of debug output into my logfiles like:
>>>>> recv: 0x11 0xc1 extra data: 0xfd 0xed 0xff 0x13 0x24 0x44 0x64 0xeb 0xa
>>>...
0
votes
1
answer
75
views
My API returns 500 on successful run, but not when run manually in debug
When I run my code in normal way, my API endpoint returns 500. The problem is I cannot debug, as when I am running in debug mode and going line-by-line, it actually runs OK. The suspected piece of ...
0
votes
1
answer
43
views
Why does my websocket connection get blocked?
I have a simple FastAPI server with just one WebSocket endpoint. It receives a terminal command, executes it locally, and broadcasts the stdout to the client every second:
from fastapi import FastAPI, ...
-1
votes
2
answers
39
views
"Event loop is closed" while running streamlit code [closed]
I am trying to build a chatbot using my own MCP server with streamlit. But when executing the code, I am getting an exception "Event loop is closed".
For the first message I am getting the ...
-1
votes
0
answers
29
views
Why does asyncio.gather() not run my coroutines concurrently when one of them contains a blocking function, and what is the correct way to fix it? [duplicate]
I have following code:
import asyncio
import time
async def task1():
print("task1 start")
time.sleep(2) # intentionally blocking
print("task1 end")
async def task2():...
-1
votes
0
answers
36
views
Why does awaiting an async generator inside asyncio.gather cause nondeterministic hangs, and how can I iterate it concurrently without deadlocking? [closed]
I'm running into a strange issue with asyncio where using asyncio.gather() on functions that consume the same async generator causes the program to sometimes hang indefinitely. The behavior is ...
0
votes
1
answer
29
views
FastAPI: Not able to use AsyncMock to fetch mock rows from aiosqlite (async sqlite3 library) while testing the endpoint
I am using Python 3.13.2
I am trying a sample use case of using AsyncMock to simulate fetching of mock rows from DB to test my endpoint (using pytest-asyncio).
I have also included a non-mock endpoint ...
1
vote
1
answer
71
views
Why does asyncio.gather() not cancel pending tasks when one task fails?
I'm using asyncio.gather to run multiple coroutines in parallel. When one coroutine raises an exception, I expect the remaining tasks to be cancelled. However, they continue running.
import asyncio
...
2
votes
1
answer
45
views
asyncio freezes when spawning multiprocessing process on Windows but works fine on Linux
I’m experimenting with mixing asyncio and multiprocessing in Python 3.12.
On Linux, the following code works as expected — the event loop stays responsive and the child process prints normally.
On ...
2
votes
1
answer
108
views
How can I create a tool for langgaph's agent to save data in db?
I created an agent using Langgraph in Python, and I developed a tool for them to save a todo in a database. But that tool doesn't work and raises an error!
I use SQLAlchemy to connect to the DB.
This ...
0
votes
1
answer
56
views
Monitor `asyncio.create_subprocess_exec` pipes for errors
I am trying to pipe multiple Linux commands and abort if there is an error. With Popen the communicate() method waits for all commands to finish. This is why I am trying asyncio now.
I have the ...
0
votes
1
answer
82
views
I have two simple Python functions with time.sleep and reading data so I/O-bound but I don't get expected behavior from threading and asyncio
Previously I had a question on an example of multiprocessing which you can see in the following link
I used a 2 workers pool to split a sum in a function with Python multiprocessing but the timing ...
2
votes
1
answer
85
views
Can't use lock around gather in Python asyncio
For some reason, this code doesn't work on Ubuntu 20, Python 3.8.10, unless the .gather line is commented out.
It works on Ubuntu 24, Python 3.12.3 and Windows 11, Python 3.13.9.
It doesn't work on ...
1
vote
1
answer
61
views
how to make socket server propagate exceptions up to TaskGroup where they're started from?
How to make exceptions thrown from a socket server running in a task group task be propagated up to its parent TaskGroup? With given example, I'd expect to see the error raised from ...
3
votes
2
answers
96
views
Python asyncio.gather returning Future attached to differnt loop exception
I am using Python 3.13.2.
I am going through the Python asyncio tutorial here. At around 10:20 timestamp, the instructor shows an example of asyncio.gather with a coroutine accepting a Future.
Here is ...
1
vote
0
answers
83
views
How to use multiprocessing with an asyncio process and a command line subprocess?
How would I be able to start a multiprocess when one of the tasks uses Asyncio and another task uses a subprocess to run?
Here is the main function:
import asyncio
import aioprocessing
import ...
Best practices
0
votes
2
replies
81
views
Python AsyncIO Graceful shutdown
No matter how much I search (or maybe I'm searching incorrectly), I can't find a decent way to terminate my tasks in Python AsyncIO.
I know what:
- I need to bind to signals (SIGINT, SIGTERM) using ...
2
votes
1
answer
76
views
Long running asyncio tasks freeze after ~1 hour. How can I debug?
I have a long running Python application built on asyncio. It launches several background tasks that run indefinitely and occasionally performs CPU work using asyncio.to_thread. Everything works fine ...
Advice
1
vote
5
replies
150
views
How does Python differentiate between async function calls and actual I/O operations?
I understand that:
await some_async_function() doesn't yield control - it just calls the function synchronously
await some_io_function() DOES yield control to the event loop
But what's the actual ...
5
votes
2
answers
127
views
How much longer will an asyncio task sleep?
I have a long running task which is executing a coroutine that calls asyncio.sleep() with a large value.
In another task I need to know how much longer the long task will sleep. I can get the long ...
0
votes
1
answer
105
views
Parallelize asynchronous API calls in Python
I’m building a data ingestion pipeline in Python that collects data from a third-party REST API.
The API allows a maximum of 100 requests per minute, and I need to fetch data for tens of thousands of ...
2
votes
1
answer
103
views
Asynchronous listening and processing in a Pyside app
I am having difficulties integrating asyncio with Pyside.
What I want to acheive:
I have several emitters (up to 30) sending messages independently every few milliseconds (200ms) in multicast.
I have ...
1
vote
1
answer
115
views
Why are my asyncio HTTP requests not overlapping as expected for I/O?
I'm trying to make a bunch of HTTP GET requests to different endpoints of the same API. My understanding is that asyncio helps me manage concurrent I/O operations efficiently, meaning when one network ...
4
votes
1
answer
101
views
TaskGroup in Python 3.11 freezes if one task raises an exception - is it a known bug?
There are two tasks in a task group. One of them raises, the other one should be cancelled. This works fine in Python 3.12+, but freezes in Python 3.11. Older versions did not support task groups.
Is ...
1
vote
0
answers
125
views
Python Asyncio: Timed out during opening handshake
I keep getting a timeout error which I can't currently explain. I'm new to networking in Python, but I can create and interact with example websocket code. For some reason the code below hits a ...
2
votes
1
answer
67
views
Scrapy Playwright freezes after initialization ([scrapy.middleware] INFO: Enabled item pipelines:[‘carscraper.pipelines.PostgreSQLPipeline’])
After starting a spider, there is the problem with freezing on a stage when pipeline must enable. There is no errors, just scrapy-playwrigth script, but it stopes on beggining before even starts ...
8
votes
2
answers
422
views
Why does multiprocess with "fork" fail under Python 3.14 but work in 3.13 (works only with "spawn" and "forkserver")?
The following code works fine on Python 3.13, but fails on Python 3.14 with a RuntimeError related to asyncio tasks.
If I switch the multiprocessing start method from "fork" to "spawn&...
1
vote
1
answer
77
views
FastAPI + pytest: RuntimeError: Event loop is closed when testing logout with AsyncClient
I'm testing a FastAPI application with asynchronous endpoints using pytest and httpx.AsyncClient. I have an endpoint /logout that depends on a JWT token from cookies and uses some async dependencies.
...
-2
votes
1
answer
63
views
Weird errors while trying to connect to Mega.NZ from Python via https://pypi.org/project/mega.py/ [closed]
I'm trying to connect to Mega.NZ via module https://pypi.org/project/mega.py/ with this code:
#!/usr/bin/env python3
from mega import Mega
mega = Mega()
m = mega.login("my mail", "my ...
-2
votes
1
answer
129
views
Use decorator to remove await prefix
I am working with Asyncio in an app I am making. However, I find it daunting to prefix my function calls with await.
So I want to encapsulate it in a decorator that adds the wait to the function call.
...
0
votes
1
answer
118
views
python REPL: is it possible to combine -i and -m asyncio?
I was trying to start the asyncio REPL (python -m asyncio) and to execute a script before starting the interactive REPL (python -i ./script.py). I tried re-ordering of options, the end-of-options ...
2
votes
2
answers
106
views
Why is asyncio.gather returning results in a different order than my tasks?
I’m learning about asynchronous programming in Python and testing with asyncio.
import asyncio
import random
async def worker(name):
delay = random.randint(1, 3)
await asyncio.sleep(delay)
...
0
votes
2
answers
118
views
asyncio.run with SQLAlchemy asyncio sessions works only once, then raises "Future attached to a different loop" and "another operation is in progress"
I’m running into an issue when using asyncio.run together with SQLAlchemy (async) inside a Celery task.
When I call the function the first time, it works fine.
On the second call, I get:
RuntimeError: ...
0
votes
1
answer
54
views
How to make Open FGA Async Client work with Flask + Gunicorn?
class FGAClientWrapper:
"""
A synchronous, gevent-friendly wrapper for the async OpenFGA SDK.
"""
def __init__(self, call_timeout: float | None = 10.0):
...
2
votes
2
answers
164
views
How to safely check a multiprocessing.Event in an asyncio loop without blocking?
I'm working on an asynchronous server using asyncio, but I need to monitor a multiprocessing.Event (used to signal termination from another process) inside my async event loop. Here's the simplified ...
4
votes
3
answers
263
views
Pytest in FastAPI + Postgres results in: <sys>:0: RuntimeWarning: coroutine 'Connection._cancel' was never awaited
I'm writing tests for my fastapi application that uses asynchronous posgtres connection:
# backend/database/session.py
from sqlmodel import SQLModel
from sqlmodel.ext.asyncio.session import ...
1
vote
2
answers
96
views
coroutine was never awaited with asyncio.TaskGroup
In the following code snippet, runner takes an optional semaphore. If this semaphore is provided, then all coroutines will be wrapped to handle entering the semaphore's context manager.
If I raise an ...
1
vote
4
answers
99
views
Why only creating a task will run the coroutine in python?
There is something I can't understand in this code
import asyncio
async def fetch_data(param):
print(f"Do something with {param}...")
await asyncio.sleep(param)
print(f"Done ...
2
votes
1
answer
142
views
Threading or asyncio for serial communications?
I'm running some serial commands to test connected devices under test (DUTs), & we have a need to run these in parallel/concurrently to speed up our tests. I would like some feedback on which ...
4
votes
3
answers
180
views
What happens if __del__ is defined as an async def coroutine in Python (CPython 3.12)?
I'm experimenting with asynchronous patterns in Python and was curious what happens if I define a __del__ method using async def in Python 3.12.
For example:
class MyClass:
async def __del__(self):...
0
votes
1
answer
250
views
How to run LlamaIndex ReAct agent with gpt-oss? Getting "SyntaxError: 'async for' outside async function"
I am trying to create a ReAct agent in LlamaIndex using a local gpt-oss-20b model.
I have successfully loaded my local model using HuggingFaceLLM from llama_index.llms.huggingface and it seems to be ...
2
votes
1
answer
89
views
Fetch data concurrently within for loop using asnycio
I would like to optimize my current function called process_coordinates.
import asyncio
from aiohttp import ClientSession
from tqdm.asyncio import tqdm
import pandas as pd
from streetlevel import ...
0
votes
1
answer
73
views
How to determine which asyncio task a program is hanging in
I have a maddening bug that makes it look like my code is hanging inside an asyncio.sleep() call. ie.
while condition:
print("Before Sleep")
await asyncio.sleep(0)
print("...
1
vote
0
answers
82
views
How to implement non-blocking async checks between turns in Pipecat Flows (0.0.18)?
I’m working with the latest version of Pipecat and Pipecat Flows (0.0.18), and I’m trying to implement a pattern where the bot can continue interacting with the user while an async background task ...
0
votes
1
answer
654
views
Discord voice WebSocket 4006 "Session is no longer valid" error with Nextcord (classic prefix command)
I’m developing a Discord bot in Python using Nextcord, with classic prefix commands. I want the bot to join a voice channel when a user sends a command.
However, when running the voice join command, ...
4
votes
3
answers
404
views
How to limit asyncio HTTP requests to N per second while processing results immediately?
How can I throttle API requests in Python’s asyncio so that no more than 5 requests are sent per second, while still processing results as soon as they arrive?
I’m working with an asynchronous HTTP ...
0
votes
1
answer
109
views
asyncio.run() raise "RuntimeError: Event loop is closed" in a Jupyter Notebook
I'm trying to run an async function inside a Jupyter Notebook using asyncio.run() like this:
import asyncio
async def my_task():
await asyncio.sleep(1)
return "Done"
asyncio.run(...
3
votes
1
answer
89
views
How to avoid double checks with asyncio.Lock
I have a piece of code, that checks if the redis db has data updates and loads them to the memory. I want only one corouitine to execute this load.
class MyService:
def __init__(self):
...
0
votes
0
answers
132
views
Input audio from microphone not collected when audio is reproduced
I'm developing a simple real-time voice bot using the OpenAI real-time API, specifically integrating with Semantic Kernel. The code is written in an async manner, and it initially works well. However, ...