Skip to content

Instantly share code, notes, and snippets.

@jcppkkk jcppkkk/tasks.py
Created Mar 15, 2019

Embed
What would you like to do?
Show Traceback when pyinvoke command fails
import sys
import traceback
from invoke import task, Context
old_run = Context.run
def new_run(self, command, **kwargs):
try:
old_run(self, command, **kwargs)
except Exception:
if "hide" in kwargs and kwargs["hide"]:
# When with hide=True
exc_type, exc_value, tb = sys.exc_info()
lines = list(traceback.TracebackException(type(exc_value), "", tb).format(chain=True))
lines[-1] = lines[-1].strip()
print("".join(lines) + ": ", file=sys.stderr, end="")
# Exception msg will print after this
else:
traceback.print_exc()
raise
Context.run = new_run
@task
def cmd(c):
c.run("false")
@task
def cmd_hide(c):
c.run("false", hide=True)
$ inv cmd
Traceback (most recent call last):
File "./tasks.py", line 11, in new_run
old_run(self, command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/context.py", line 94, in run
return self._run(runner, command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/context.py", line 101, in _run
return runner.run(command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/runners.py", line 271, in run
return self._run_body(command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/runners.py", line 404, in _run_body
raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!
Command: 'false'
Exit code: 1
Stdout: already printed
Stderr: already printed
$ inv cmd-hide
Traceback (most recent call last):
File "./tasks.py", line 11, in new_run
old_run(self, command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/context.py", line 94, in run
return self._run(runner, command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/context.py", line 101, in _run
return runner.run(command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/runners.py", line 271, in run
return self._run_body(command, **kwargs)
File "./.venv/lib/python3.6/site-packages/invoke/runners.py", line 404, in _run_body
raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!
Command: 'false'
Exit code: 1
Stdout:
Stderr:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.