如何接收python异常消息?
因此,我有一些代码:如何接收python异常消息?,python,python-3.x,Python,Python 3.x,因此,我有一些代码: try: subprocess.check_call( "mysqldump {} {}".format(mysql_args, cmd), shell=True ) except Exception as e: raise Exception("Command failed") 问题在于,应用程序中其他地方的异常日志记录代码捕获了该异常,并将其打印出来——在本例中,该代码如下所示: Traceback (most recent c
try:
subprocess.check_call(
"mysqldump {} {}".format(mysql_args, cmd), shell=True
)
except Exception as e:
raise Exception("Command failed")
问题在于,应用程序中其他地方的异常日志记录代码捕获了该异常,并将其打印出来——在本例中,该代码如下所示:
Traceback (most recent call last):
File "/apps/django/myapp/tasks.py", line 336, in _safe_mysqldump
"mysqldump {} {}".format(mysql_args, cmd), shell=True
File "/usr/lib/python3.6/subprocess.py", line 291, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError:
Command 'mysqldump -ufoo -pMYSECRETPASSWORD myappdb t1 t2 t3...' returned non-zero exit status 6.
During handling of the above exception, another exception occurred:
etc.
failed = False
try:
...
except Exception:
failed = True
finally:
if failed:
raise Exception("Command failed")
关键是它打印出了mysql连接字符串。如何防止它这样做?您可以这样更改输出:
Traceback (most recent call last):
File "/apps/django/myapp/tasks.py", line 336, in _safe_mysqldump
"mysqldump {} {}".format(mysql_args, cmd), shell=True
File "/usr/lib/python3.6/subprocess.py", line 291, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError:
Command 'mysqldump -ufoo -pMYSECRETPASSWORD myappdb t1 t2 t3...' returned non-zero exit status 6.
During handling of the above exception, another exception occurred:
etc.
failed = False
try:
...
except Exception:
failed = True
finally:
if failed:
raise Exception("Command failed")
使用以下语法:
raise Exception("Command failed") from None
见):
或
if subprocess.call()!=0:
引发异常(“命令失败”)
if subprocess.run(<command>).returncode != 0:
raise Exception("Command failed")
if subprocess.call(<command>) != 0:
raise Exception("Command failed")