How to log errors in python when using the os module
python
Solution
`os.system()` returns an integer result code. When it returns 0, the command ran successfully; when it returns a nonzero value, that indicates an error.
db_dump = "mysqldump -u %s -p%s --socket=source_socket --databases %s | mysql -u %s -p%s --socket=dest_socket" % (db_user, db_pass, ' '.join(db_list), db_user, db_pass)
result = os.system(db_dump)
if 0 == result:
logging.info("database dump complete")
else:
logging.error("databases did not dump; result code: %d" % result)
Like @COpython, I recommend the use of `subprocess`. It is a bit more complicated than `os.system()` but it is tremendously more flexible. With `os.system()` the output is sent to the terminal, but with `subprocess` you can collect the output so you can search it for error messages or whatever. Or you can just discard the output.
Problem
I'm trying to incorporate a simple way to keep track of a periodic mysqldump command I want to run using the os module in python. I've written this, but in testing it doesn't raise the exception, even when the mysqldump command completes with an error. I'm pretty new to python, so I might be approaching this terribly, but I thought I would try to get pointed in the right direction. ``` db_dump = "mysqldump -u %s -p%s --socket=source_socket --databases %s | mysql -u %s -p%s --socket=dest_socket" % (db_user, db_pass, ' '.join(db_list), db_user, db_pass) try: os.system(db_dump) except: logging.error("databases did not dump") else: logging.info("database dump complete") ```