如果我将其与 psycopg2 一起使用,如何打印 RAISE NOTICE 输出?

问题描述 投票:0回答:1

我正在尝试在循环期间打印:

WHILE (batch_offset < total_records) LOOP

-- query code

-- Get and display the number of rows processed
    GET DIAGNOSTICS rows_processed = ROW_COUNT;
    current_record := current_record + rows_processed;
    -- RAISE NOTICE 'Current record: %', current_record;

    -- Calculate and print percent complete
    percentage_complete := (current_record::NUMERIC / total_records::NUMERIC) * 100;
    RAISE NOTICE 'Completion percentage: %', ROUND(percentage_complete, 2);

    -- Increment the offset for the next batch
    batch_offset := batch_offset + batch_size;

END LOOP;

使用此代码:

with psycopg2.connect(**kargs) as conn:
            with conn.cursor() as cur:
            cur.execute(loop_query)

我应该在执行之后或之前添加什么代码来拦截每个周期生成的通知?

我尝试执行后,这个:

while conn.notices:
        notice = conn.notices.pop(0)
        print(notice)

但它没有给我我想要的。

linux postgis psycopg2 python-3.10 postgresql-16
1个回答
0
投票

一个简单的例子。

import psycopg2

loop_qry = """DO
$$
DECLARE
    ct integer := 0;
BEGIN
    WHILE ct < 5 LOOP
        RAISE NOTICE 'Loop counter = %', ct;
        ct = ct + 1;
    END LOOP;
END;

$$
"""
with psycopg2.connect("dbname=test user=aklaver port=5432") as con:
    cur = con.cursor()
    cur.execute(loop_qry)
    for notice in con.notices:
        print(notice)
NOTICE:  Loop counter = 0

NOTICE:  Loop counter = 1

NOTICE:  Loop counter = 2

NOTICE:  Loop counter = 3

NOTICE:  Loop counter = 4

© www.soinside.com 2019 - 2024. All rights reserved.