Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Last active January 28, 2025 21:48
Show Gist options
  • Save mattfysh/829f4f0477b928e4be2b9974b3725670 to your computer and use it in GitHub Desktop.
Save mattfysh/829f4f0477b928e4be2b9974b3725670 to your computer and use it in GitHub Desktop.
import os
import sys
import json
from time import sleep
# if we open the fd before bun has written to it
# we'll get a "bad fd" error :\
sleep(1)
fd = 3
read_pipe = os.fdopen(fd, "r")
write_pipe = os.fdopen(fd, "w")
def read():
line = read_pipe.readline()
print("[py]: bun -> py -> @raw", line.encode())
# TMP: fix bun bug - @see https://github.com/oven-sh/bun/issues/13799
if len(line) > 0 and line[0] == "\x01":
line = line[1:]
line = line.strip()
if not line:
sys.exit(0)
msg = json.loads(line)
print("[py]: bun -> py -> @json", msg)
return msg
def write(msg):
print("[py]: py -> bun", msg)
write_pipe.write(json.dumps(msg) + "\n")
write_pipe.flush()
while True:
try:
msg = read()
write("msg recvd")
except EOFError:
break
import { spawn } from 'bun'
const proc = spawn({
cmd: ['python3', 'index.py'],
serialization: 'json',
stdio: ['inherit', 'inherit', 'inherit'],
ipc(msg) {
console.log('[bun] py -> bun:', msg)
},
onExit(subprocess, exitCode, signalCode, error) {
console.log('python process ended with exit code', exitCode, signalCode)
if (error) console.error(error)
},
})
function send(msg: any) {
console.log('[bun] bun -> py:', msg)
proc.send(msg)
}
send('0 mark')
setTimeout(() => {
send('2000 mark')
}, 2000)
setTimeout(() => {
send('4000 mark')
}, 4000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment