我正在尝试使用一种简单的方法来跟踪我想在python中使用os模块运行的周期性mysqldump命令。我写过这个,但在测试中它不会引发异常,即使mysqldump命令因错误而完成。我对python很新,所以我可能会非常接近这个,但我想我会试着指向正确的方向。
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")
答案 0 :(得分:4)
os.system不是一种非常强大或强大的方法来调用系统命令,我建议使用subprocess.check_output()
或subprocess.check_call
即
>>> cmd = 'ls -l'
>>> badcmd = 'ls /foobar'
>>> subprocess.check_call(cmd.split())
0
>>> subprocess.check_call(badcmd.split())
ls: /foobar: No such file or directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 511, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['ls', '/foobar']' returned non-zero exit status 1
答案 1 :(得分:2)
os.system()
返回整数结果代码。当它返回0时,命令成功运行;当它返回非零值时,表示错误。
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)
与@COpython一样,我建议使用subprocess
。它比os.system()
复杂一点,但它更灵活。使用os.system()
将输出发送到终端,但使用subprocess
,您可以收集输出,以便搜索错误消息或其他内容。或者你可以放弃输出。
答案 2 :(得分:1)
这就是我要做的事。
import logging
import subprocess
log = logging.getLogger(__name__)
cmd = "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)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE.PIPE)
stdout, stderr = process.communicate()
stdout = [x for x in stdout.split("\n") if x != ""]
stderr = [x for x in stderr.split("\n") if x != ""]
if process.returncode < 0 or len(stderr):
for error in stderr:
log.error(error)