import subprocess, sys, os, time, threading NL = chr(10) interp = sys.argv[1] script = sys.argv[2] infile = sys.argv[3] oneshot = (len(sys.argv) > 4 and sys.argv[4] == '1') args = sys.argv[7:] if len(sys.argv) > 7 else [] dbgpath = infile + '.dbg' def dlog(m): try: with open(dbgpath, 'a', encoding='utf-8', errors='replace') as d: d.write('[' + time.strftime('%H:%M:%S') + '] ' + m + NL) except Exception: pass dlog('pyfeed start interp=%r oneshot=%s args=%r' % (interp, oneshot, args)) env = dict(os.environ) env['PYTHONUNBUFFERED'] = '1' env['PYTHONWARNINGS'] = 'ignore' env['PYTHONDONTWRITEBYTECODE'] = '1' codepath = infile[:-3] + '.code' if os.path.isfile(codepath): try: os.remove(codepath) except Exception: pass def reader(p): try: while True: b = p.stdout.read(1) if not b: break sys.stdout.buffer.write(b) sys.stdout.flush() except Exception as e: dlog('reader exception: %r' % (e,)) if oneshot: try: fin = open(infile, 'rb') except Exception as e: dlog('FATAL cannot open infile: %r' % (e,)) sys.exit(2) dlog('oneshot: stdin=file, %d bytes' % os.path.getsize(infile)) p = subprocess.Popen([interp, script] + args, stdin=fin, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, cwd=(os.path.dirname(script) or os.getcwd())) threading.Thread(target=reader, args=(p,), daemon=True).start() p.wait() code = p.returncode if p.returncode is not None else 0 dlog('oneshot: child exited rc=%s' % code) try: with open(codepath, 'w') as c: c.write(str(code)) except Exception: pass sys.exit(code) p = subprocess.Popen([interp, script] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, cwd=(os.path.dirname(script) or os.getcwd()), bufsize=0) dlog('interactive: child pid=%s' % p.pid) threading.Thread(target=reader, args=(p,), daemon=True).start() pos = 0 def feed(data): for ln in data.splitlines(): try: p.stdin.write((ln + NL).encode('utf-8')) p.stdin.flush() dlog('WROTE line: %r' % ln[:80]) except BrokenPipeError: dlog('WRITE FAILED: broken pipe') return False except Exception as e: dlog('WRITE FAILED line=%r exc=%r' % (ln[:80], e)) return False return True while p.poll() is None: try: with open(infile, 'r', encoding='utf-8', errors='replace') as fh: fh.seek(pos) data = fh.read() if data: pos = fh.tell() if not feed(data): break except Exception as e: dlog('read infile exception: %r' % (e,)) time.sleep(0.25) code = p.returncode if p.returncode is not None else 0 dlog('interactive: child exited rc=%s' % code) try: with open(codepath, 'w') as c: c.write(str(code)) except Exception: pass sys.exit(code)