python_startup.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2015 Stefano Mazzucco <stefano - at - curso - dot - re>
  2. # This program is free software: you can redistribute it and/or modify
  3. # it under the terms of the GNU General Public License as published by
  4. # the Free Software Foundation, either version 3 of the License, or
  5. # (at your option) any later version.
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. # You should have received a copy of the GNU General Public License
  11. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. import os
  13. import sys
  14. import rlcompleter
  15. import readline
  16. readline.parse_and_bind('tab: complete')
  17. del rlcompleter, readline
  18. # ANSI colors
  19. END_COLOR = '\033[0m'
  20. YELLOW = '\033[33m'
  21. RED = '\033[31m'
  22. try:
  23. import builtins as __builtins__
  24. except ImportError:
  25. # Python 2
  26. import __builtin__ as __builtins__
  27. class PromptCounter(object):
  28. def __init__(self, in_fmt, out_fmt):
  29. self.count = 1
  30. self._in_fmt = in_fmt
  31. self._out_fmt = out_fmt
  32. def __str__(self):
  33. current = self._in_fmt.format(self.count)
  34. self.count += 1
  35. return current
  36. def __call__(self, value):
  37. # Only useful in sys.displayhook
  38. # https://docs.python.org/3/library/sys.html#sys.displayhook
  39. if value is None:
  40. return
  41. # Set '_' to None to avoid recursion
  42. __builtins__._ = None
  43. # __call__ is called before __str__ so, format with count
  44. # decremented by 1 to keep the two in sync
  45. sys.stdout.write(''.join(
  46. [self._out_fmt.format(self.count - 1), repr(value), '\n']))
  47. __builtins__._ = value
  48. if __name__ == '__main__':
  49. if not os.environ.get('INSIDE_EMACS'):
  50. sys.ps1 = sys.displayhook = PromptCounter(
  51. YELLOW + '[In {}]:' + END_COLOR + ' ',
  52. RED + '[Out {}]:' + END_COLOR + ' ')
  53. del YELLOW, RED, END_COLOR, PromptCounter