I was curious about how hard it would be to implement something like pypipe[1] in go. Turns out, not that hard.
[1] https://github.com/bugen/pypipe
$ echo "foo bar" | go run main.go 4
b
I was curious about how hard it would be to implement something like pypipe[1] in go. Turns out, not that hard.
[1] https://github.com/bugen/pypipe
$ echo "foo bar" | go run main.go 4
b
module gream | |
go 1.21.3 | |
require github.com/traefik/yaegi v0.15.1 |
github.com/traefik/yaegi v0.15.1 h1:YA5SbaL6HZA0Exh9T/oArRHqGN2HQ+zgmCY7dkoTXu4= | |
github.com/traefik/yaegi v0.15.1/go.mod h1:AVRxhaI2G+nUsaM1zyktzwXn69G3t/AuTDrCiTds9p0= |
package main | |
// silly pypipe poc in go: https://github.com/bugen/pypipe | |
// 2023 @leonjza | |
import ( | |
"os" | |
"strings" | |
"github.com/traefik/yaegi/interp" | |
"github.com/traefik/yaegi/stdlib" | |
) | |
func main() { | |
var col string | |
if len(os.Args) <= 1 { | |
col = "0" | |
} else { | |
col = os.Args[1] | |
} | |
i := interp.New(interp.Options{}) | |
i.Use(stdlib.Symbols) | |
_, err := i.Eval(`import "bufio"`) | |
if err != nil { | |
panic(err) | |
} | |
_, err = i.Eval(`import "fmt"`) | |
if err != nil { | |
panic(err) | |
} | |
_, err = i.Eval(`import "os"`) | |
if err != nil { | |
panic(err) | |
} | |
_, err = i.Eval(`import "strings"`) | |
if err != nil { | |
panic(err) | |
} | |
lineProcessor := ` | |
s := bufio.NewScanner(os.Stdin) | |
for s.Scan() { | |
l := strings.TrimSpace(s.Text()) | |
fmt.Println(string(l[COLUMN])) | |
} | |
` | |
lineProcessor = strings.Replace(lineProcessor, `COLUMN`, col, 1) | |
_, err = i.Eval(lineProcessor) | |
if err != nil { | |
panic(err) | |
} | |
} |