0

I have the following code

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)

When it runs it sends out an email about the error. I get the email but all I get is

An Error has occured for job JOB. Import did not complete.

Error 1 running mysql query:

When I run the procedure in in an EDI (like Toad) I get

Column count doesn't match value count at row 1

How can I get the MySQL error message in the EMail? It doesn't seem to be in ex.output.

Note
The error comes from my commenting out a field in an INSERT INTO ... SELECT query. I have done this on purpose to trigger the exception.

1 Answer 1

1

subprocess.check_output() does not return stderr by default. As the doc string says:

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 is package relative, so you'd use subprocess.STDOUT.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.