我有以下代码
def exec_sql_query(query):
output = subprocess.check_output(
[
"mysql",
"-h", config.sos.server,
"-u", config.sos.username,
"-p" + config.sos.password,
"-D", config.sos.dataloaddatabase,
"-sNL","--local-infile","-e",query
])
return output.rstrip()
def email_notification_error(job_name, error_msg):
server = smtplib.SMTP(email_server)
server.set_debuglevel(1)
body = "<html><div>An Error has occured for job {0}. Import did not complete.<br /><br />{1}</div></html>".fo$
msg = MIMEText(body, 'html')
msg['Subject'] = "Error Importing {0}. {1}".format(job_name, test_environment)
msg['From'] = email_from
msg['To'] = ','.join(email_to)
server.sendmail(email_from,email_to,msg.as_string())
server.quit()
#Main Entry Point
try
exec_sql_query(refresh_query)
except subprocess.CalledProcessError as ex:
error_msg = "Error {0} running mysql query: {1}".format(ex.returncode, ex.output)
logger.error(error_msg)
email_notification_error(job_name, error_msg)
运行时会发送有关错误的电子邮件。我收到了电子邮件,但我得到的只是
作业JOB出现错误。导入没有完成。
错误1运行mysql查询:
当我在EDI(如Toad)中运行该程序时,我得到了
列数与第1行的值计数不匹配
如何在电子邮件中获取MySQL错误消息?它似乎不在ex.output
。
注意
该错误来自于我在INSERT INTO ... SELECT
查询中注释了一个字段。我故意这样做是为了触发异常。
答案 0 :(得分:1)
subprocess.check_output()默认情况下不返回stderr。正如文档字符串所示:
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
STDOUT是包相对的,所以你要使用subprocess.STDOUT。