traceback_run.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python3
  2. # Import as few modules and define as few names as possible at global level before exec'ing the
  3. # file, as all names will be seen by the exec'ed file. To prevent name collisions, all names
  4. # defined here should begin with 'traceback_run_'
  5. import sys,os,time
  6. def traceback_run_init():
  7. import os
  8. sys.path[0] = 'test' if os.path.dirname(sys.argv[1]) == 'test' else '.'
  9. if 'TMUX' in os.environ: del os.environ['TMUX']
  10. os.environ['MMGEN_TRACEBACK'] = '1'
  11. os.environ['PYTHONPATH'] = '.'
  12. of = 'my.err'
  13. try: os.unlink(of)
  14. except: pass
  15. return of
  16. def traceback_run_process_exception():
  17. import traceback,re
  18. lines = traceback.format_exception(*sys.exc_info()) # returns a list
  19. pat = re.compile('File "<string>"')
  20. repl = f'File "{traceback_run_execed_file}"'
  21. lines = [pat.sub(repl,line,count=1) for line in lines]
  22. exc = lines.pop()
  23. if exc.startswith('SystemExit:'):
  24. lines.pop()
  25. if False: # was: if os.getenv('MMGEN_DISABLE_COLOR'):
  26. sys.stdout.write('{}{}'.format(''.join(lines),exc))
  27. else:
  28. yellow = lambda s: f'\033[33;1m{s}\033[0m'
  29. red = lambda s: f'\033[31;1m{s}\033[0m'
  30. sys.stdout.write('{}{}'.format(yellow(''.join(lines)),red(exc)))
  31. open(traceback_run_outfile,'w').write(''.join(lines+[exc]))
  32. traceback_run_outfile = traceback_run_init()
  33. traceback_run_tstart = time.time()
  34. try:
  35. sys.argv.pop(0)
  36. traceback_run_execed_file = sys.argv[0]
  37. exec(open(sys.argv[0]).read())
  38. except SystemExit as e:
  39. if e.code != 0:
  40. traceback_run_process_exception()
  41. sys.exit(e.code)
  42. except Exception as e:
  43. traceback_run_process_exception()
  44. retval = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  45. sys.exit(retval)
  46. blue = lambda s: s if os.getenv('MMGEN_DISABLE_COLOR') else '\033[34;1m{}\033[0m'.format(s)
  47. sys.stderr.write(blue('Runtime: {:0.5f} secs\n'.format(time.time() - traceback_run_tstart)))