Skip to content

Instantly share code, notes, and snippets.

@filevich
Last active May 28, 2021 06:08

Revisions

  1. filevich revised this gist May 28, 2021. No changes.
  2. filevich created this gist Jan 31, 2021.
    39 changes: 39 additions & 0 deletions driver.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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)
    35 changes: 35 additions & 0 deletions stub.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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
    }
    }
    }
    }