psql命令嵌入python代码时如何捕捉错误信息?

snz8szmq  于 2023-02-17  发布在  Python
关注(0)|答案(1)|浏览(128)

可以在bash控制台中导入数据:

psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  with delimiter ',' "
Pager usage is off.
Timing is on.
COPY 1
Time: 9.573 ms

我删除了with delimiter子句以创建错误:

psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  "
Pager usage is off.
Timing is on.
ERROR:  missing data for column "f2"
CONTEXT:  COPY data, line 1: ""x1","y1""
Time: 0.318 ms

所有的错误信息显示在bash控制台,我想捕捉错误信息时,psql命令嵌入python代码:

import os 
import logging
logging_file = '/tmp/log.txt' 
logging.basicConfig(filename=logging_file,level=logging.INFO,filemode='a+')
logger = logging.getLogger("import_data")

sql_string ="""
psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  " 
"""

try:
    os.system(sql_string)
except Exception as e:
    logger.info(e)

为什么错误信息不能写入日志文件/tmp/log.txt?当psql命令嵌入python代码时,如何捕获错误信息?

eyh26e7m

eyh26e7m1#

os.system()产生的错误可能未被try块捕获。如果命令失败,os.system()可能引发OSError,但try块可能未引发和捕获该错误。
您可以使用subprocess模块而不是os.system()来运行命令并捕获输出和错误流
请尝试以下代码:

import logging
import subprocess
sql_string = """ psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  " """
logging_file = './log.txt'
logging.basicConfig(filename=logging_file, level=logging.DEBUG, filemode='a+')
try:
    result = subprocess.run(['psql', '-U', 'postgres', '-d', 'sample', '-c', 'copy data(f1,f2) from \'/tmp/data.txt\''],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise Exception(result.stderr.decode('utf-8'))
except Exception as e:
    logging.info(e)
    # The below line will help to get traceback of exception.
    # logging.exception(e)

相关问题