gpt4 book ai didi

python - 我怎样才能吞掉Python异常消息?

转载 作者:行者123 更新时间:2023-12-01 01:33:13 24 4
gpt4 key购买 nike

我有一些代码:

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.

关键是它打印出了 mysql 连接字符串。我怎样才能阻止它这样做?

最佳答案

使用语法:

raise Exception("Command failed") from None

参见PEP 409 Suppressing exception context ):

>>> try:
... raise TypeError('a')
... except TypeError:
... raise ValueError('b') from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: b

与您看到的默认行为相比:

>>> try:
... raise TypeError('a')
... except TypeError:
... raise ValueError('b')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: a

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: b
<小时/>

作为特定于您的用例的替代方案:不要使用会引发异常的 check_call ,而是使用 subprocess.run 相反:

if subprocess.run(<command>).returncode != 0:
raise Exception("Command failed")

subprocess.call

if subprocess.call(<command>) != 0:
raise Exception("Command failed")

关于python - 我怎样才能吞掉Python异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com