如何在嵌入在Python代码中的psql命令中捕获错误信息?

huangapple go评论55阅读模式
英文:

How can catch the error info when psql command embedded in python code?

问题

以下是翻译好的内容:

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

    psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  with delimiter ',' "
    停用了分页器使用。
    打开了计时。
    复制了 1 条记录
    时间:9.573 毫秒

我移除了 `with delimiter` 子句以引发错误:

    psql -U postgres -d sample -c "copy data(f1,f2) from '/tmp/data.txt'  "
    停用了分页器使用。
    打开了计时。
    错误:缺少列 "f2" 的数据
    上下文:复制数据,第 1 行:""x1","y1""
    时间:0.318 毫秒

所有的错误信息都显示在bash控制台上,我想在嵌入在Python代码中的psql命令中捕获错误信息:

    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)

希望这有所帮助。如果您有其他翻译需求,请随时提问。

英文:

The data can be imported in bash console:

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

I remove with delimiter clause to create an error:

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

All the error info shown on the bash console,i want to catch the error info when psql command embedded in python code:

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)

Why the error info can't be written into the log file /tmp/log.txt?How can catch the error info when psql command embedded in python code?

答案1

得分: 1

以下是翻译好的部分:

It is likely that the error produced by os.system() is not being captured by the try-block. os.system() can raise an OSError if the command fails, but it is possible that the error is not being raised and caught by the try block.

可能是由于 os.system() 生成的错误没有被 try 块捕获。os.system() 如果命令执行失败可能会引发 OSError,但可能错误没有被 try 块捕获。

You can use the subprocess module instead of os.system() to run the command and capture the output and error streams.

你可以使用 subprocess 模块代替 os.system() 来运行命令并捕获输出和错误流。

Try this code:

尝试使用以下代码:

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)

导入 logging
导入 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+')
尝试:
result = subprocess.run(['psql', '-U', 'postgres', '-d', 'sample', '-c', 'copy data(f1,f2) from '/tmp/data.txt''],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
如果 result.returncode != 0:
引发异常(result.stderr.decode('utf-8'))
除非 异常 as e:
logging.info(e)
# 下面的代码将帮助获取异常的回溯信息。
# logging.exception(e)

英文:

It is likely that the error produced by os.system() is not being captured by the try-block. os.system() can raise an OSError if the command fails, but it is possible that the error is not being raised and caught by the try block.

You can use the subprocess module instead of os.system() to run the command and capture the output and error streams

Try this code:

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)

huangapple
  • 本文由 发表于 2023年2月10日 13:10:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定