diff --git a/langchain/utilities/docker/pexpect_exec.py b/langchain/utilities/docker/pexpect_exec.py new file mode 100644 index 00000000..db55d382 --- /dev/null +++ b/langchain/utilities/docker/pexpect_exec.py @@ -0,0 +1,32 @@ +import pexpect + +def interact_with_python_shell(child: pexpect.spawn, **kwargs) -> str: + """Interact with a Python shell running in a pexpect spawn instance.""" + try: + child.expect(">>>", **kwargs) + except pexpect.exceptions.TIMEOUT: + print("no data") + return child.before.strip() + buf = "" + max_reads=5 + read_cnt=0 + while True: + if read_cnt > max_reads: + print("reached max depth") + break + try: + child.expect("\n>>>", **kwargs) + result = child.before.strip() + if len(result) > 0: + buf += result + "\n" + except pexpect.exceptions.TIMEOUT: + # The child process is still running, but it's not outputting anything. + # Wait a bit and try again. + #TODO: add trial times before exit + read_cnt += 1 + continue + except pexpect.exceptions.EOF: + # The child process has exited. + print("EOF") + break + return buf