Skip to content

Instantly share code, notes, and snippets.

@filevich
Last active May 28, 2021 06:08
Show Gist options
  • Save filevich/8d85e221bf4e197d9a9f684d1b02e4a7 to your computer and use it in GitHub Desktop.
Save filevich/8d85e221bf4e197d9a9f684d1b02e4a7 to your computer and use it in GitHub Desktop.
python driver and go stub; execute Go from Python
import subprocess
cmd = ['./stub']
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
def consume(std, fn):
while True:
line = std.readline()
if not line:
break
fn(line)
printer = lambda bs: print(b'-->' + bs)
# To avoid deadlocks: careful to: add \n to output, flush output, use
# readline() rather than read()
proc.stdin.write(b'{"fruta": 33}\n')
proc.stdin.flush()
print(proc.stdout.readline())
proc.stdin.write(b'{"fruta": 66}\n')
proc.stdin.flush()
print(proc.stdout.readline())
proc.stdin.write(b'{"fruta": -1}\n')
proc.stdin.flush()
consume(proc.stderr, printer)
consume(proc.stdout, printer)
proc.stdin.close()
proc.terminate()
proc.wait(timeout=0.2)
package main
/*
go build stub.go
*/
import (
"encoding/json"
"fmt"
"log"
"os"
)
type MedicalRecord struct {
Fruta int `json:"fruta"`
}
func main() {
var record MedicalRecord
for {
err := json.NewDecoder(os.Stdin).Decode(&record)
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("ok: parsed %d\n", record.Fruta)
if record.Fruta == -1 {
fmt.Println("bye bye")
fmt.Fprintf(os.Stderr, "forbidden number: %d\n", record.Fruta)
fmt.Fprintf(os.Stderr, "yada yada\n")
return
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment