Reputation: 1005
I have some code thus:
try:
subprocess.check_call(
"mysqldump {} {}".format(mysql_args, cmd), shell=True
)
except Exception as e:
raise Exception("Command failed")
The problem is that Exception logging code elsewhere in the application catches this exception and helpfully prints it out - which in this case looks like this:
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.
The critical thing being it printed out the mysql connection string. How can I prevent it from doing this?
Upvotes: 1
Views: 1474
Reputation: 2479
Use the syntax:
raise Exception("Command failed") from None
See 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
Versus the default behaviour which you saw:
>>> 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
As an alternative specific to your use case: do not use check_call
which raises an exception but use subprocess.run
instead:
if subprocess.run(<command>).returncode != 0:
raise Exception("Command failed")
if subprocess.call(<command>) != 0:
raise Exception("Command failed")
Upvotes: 3
Reputation:
You may change the output like this:
failed = False
try:
...
except Exception:
failed = True
finally:
if failed:
raise Exception("Command failed")
Upvotes: 0