可以在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代码时,如何捕获错误信息?
1条答案
按热度按时间eyh26e7m1#
os.system()
产生的错误可能未被try块捕获。如果命令失败,os.system()
可能引发OSError
,但try块可能未引发和捕获该错误。您可以使用
subprocess
模块而不是os.system()
来运行命令并捕获输出和错误流请尝试以下代码: