You can check the connection status:
from psycopg2.extensions import STATUS_BEGIN, STATUS_READY
if conn.status == STATUS_READY:
print("No transaction in progress.")
elif conn.status == STATUS_BEGIN:
print("A transaction is in progress.")
Alternatively, transaction status can be obtained with connection.get_transaction_status().
To manually verify a transaction in a process, you can use the PostgreSQL statistics collector :
SELECT * FROM pg_stat_activity WHERE state = 'idle in transaction';
source
share