oepydevshell-internal.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import time
  5. import select
  6. import fcntl
  7. import termios
  8. import readline
  9. import signal
  10. def nonblockingfd(fd):
  11. fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  12. def echonocbreak(fd):
  13. old = termios.tcgetattr(fd)
  14. old[3] = old[3] | termios.ECHO | termios.ICANON
  15. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  16. def cbreaknoecho(fd):
  17. old = termios.tcgetattr(fd)
  18. old[3] = old[3] &~ termios.ECHO &~ termios.ICANON
  19. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  20. if len(sys.argv) != 3:
  21. print("Incorrect parameters")
  22. sys.exit(1)
  23. pty = open(sys.argv[1], "w+b", 0)
  24. parent = int(sys.argv[2])
  25. nonblockingfd(pty)
  26. nonblockingfd(sys.stdin)
  27. histfile = os.path.expanduser("~/.oedevpyshell-history")
  28. readline.parse_and_bind("tab: complete")
  29. try:
  30. readline.read_history_file(histfile)
  31. except IOError:
  32. pass
  33. try:
  34. i = ""
  35. o = ""
  36. # Need cbreak/noecho whilst in select so we trigger on any keypress
  37. cbreaknoecho(sys.stdin.fileno())
  38. # Send our PID to the other end so they can kill us.
  39. pty.write(str(os.getpid()).encode('utf-8') + b"\n")
  40. while True:
  41. try:
  42. writers = []
  43. if i:
  44. writers.append(sys.stdout)
  45. (ready, _, _) = select.select([pty, sys.stdin], writers , [], 0)
  46. try:
  47. if pty in ready:
  48. i = i + pty.read().decode('utf-8')
  49. if i:
  50. # Write a page at a time to avoid overflowing output
  51. # d.keys() is a good way to do that
  52. sys.stdout.write(i[:4096])
  53. sys.stdout.flush()
  54. i = i[4096:]
  55. if sys.stdin in ready:
  56. echonocbreak(sys.stdin.fileno())
  57. o = input().encode('utf-8')
  58. cbreaknoecho(sys.stdin.fileno())
  59. pty.write(o + b"\n")
  60. except (IOError, OSError) as e:
  61. if e.errno == 11:
  62. continue
  63. if e.errno == 5:
  64. sys.exit(0)
  65. raise
  66. except EOFError:
  67. sys.exit(0)
  68. except KeyboardInterrupt:
  69. os.kill(parent, signal.SIGINT)
  70. except SystemExit:
  71. pass
  72. except Exception as e:
  73. import traceback
  74. print("Exception in oepydehshell-internal: " + str(e))
  75. traceback.print_exc()
  76. time.sleep(5)
  77. finally:
  78. readline.write_history_file(histfile)