Run bpython (with `backend` as backend) in a subprocess and enter the given input. Uses a test config that disables the paste detection. Returns bpython's output.
(self, input)
| 39 | backend = "cli" |
| 40 | |
| 41 | def run_bpython(self, input): |
| 42 | """ |
| 43 | Run bpython (with `backend` as backend) in a subprocess and |
| 44 | enter the given input. Uses a test config that disables the |
| 45 | paste detection. |
| 46 | |
| 47 | Returns bpython's output. |
| 48 | """ |
| 49 | result = Deferred() |
| 50 | encoding = getpreferredencoding() |
| 51 | |
| 52 | class Protocol(ProcessProtocol): |
| 53 | STATES = (SEND_INPUT, COLLECT) = range(2) |
| 54 | |
| 55 | def __init__(self): |
| 56 | self.data = "" |
| 57 | self.delayed_call = None |
| 58 | self.states = iter(self.STATES) |
| 59 | self.state = next(self.states) |
| 60 | |
| 61 | def outReceived(self, data): |
| 62 | self.data += data.decode(encoding) |
| 63 | if self.delayed_call is not None: |
| 64 | self.delayed_call.cancel() |
| 65 | self.delayed_call = reactor.callLater(0.5, self.next) |
| 66 | |
| 67 | def next(self): |
| 68 | self.delayed_call = None |
| 69 | if self.state == self.SEND_INPUT: |
| 70 | index = self.data.find(">>> ") |
| 71 | if index >= 0: |
| 72 | self.data = self.data[index + 4 :] |
| 73 | self.transport.write(input.encode(encoding)) |
| 74 | self.state = next(self.states) |
| 75 | elif self.data == "\x1b[6n": |
| 76 | # this is a cursor position query |
| 77 | # respond that cursor is on row 2, column 1 |
| 78 | self.transport.write("\x1b[2;1R".encode(encoding)) |
| 79 | else: |
| 80 | self.transport.closeStdin() |
| 81 | if self.transport.pid is not None: |
| 82 | self.delayed_call = None |
| 83 | self.transport.signalProcess("TERM") |
| 84 | |
| 85 | def processExited(self, reason): |
| 86 | if self.delayed_call is not None: |
| 87 | self.delayed_call.cancel() |
| 88 | result.callback(self.data) |
| 89 | |
| 90 | (master, slave) = pty.openpty() |
| 91 | set_win_size(slave, 25, 80) |
| 92 | reactor.spawnProcess( |
| 93 | Protocol(), |
| 94 | sys.executable, |
| 95 | ( |
| 96 | sys.executable, |
| 97 | "-m", |
| 98 | f"bpython.{self.backend}", |
no test coverage detected