Communication with console applications

I am newbie. I tried to contact the go chess engine exec, but I need to close stdin. I want to create a dialogue with the engine.

How do I do this with go?

This is a python implementation of communication, which is quite simple, can be found in How to communicate with the Chess engine in Python?

    import subprocess, time

    engine = subprocess.Popen(
    'stockfish-x64.exe',
    universal_newlines=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    )

    def put(command):
    print('\nyou:\n\t'+command)
    engine.stdin.write(command+'\n')

    def get():
    # using the 'isready' command (engine has to answer 'readyok')
    # to indicate current last line of stdout
    engine.stdin.write('isready\n')
    print('\nengine:')
    while True:
        text = engine.stdout.readline().strip()
        if text == 'readyok':
            break
        if text !='':
            print('\t'+text)

    get()
    put('uci')
    get()

put('setoption name Hash value 128')
get()
put('ucinewgame')
get()
put('position startpos moves e2e4 e7e5 f2f4')
get()
put('go infinite')
time.sleep(3)
get()
put('stop')
get()
put('quit')

For simplicity, consider this in go:

package main

import ( 
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    cmd := exec.Command("stockfish")
    stdin, _ := cmd.StdinPipe()
    io.Copy(stdin, bytes.NewBufferString("isready\n"))
    var out bytes.Buffer
    cmd.Stdout = &out
    cmd.Run()
    fmt.Printf(out.String())
}

The program waits without printing anything. But when I close stdin, the program prints the result, but closing stdin prevents the data exchange between the engine and the go program.

Decision:

package main

    import ( 
        "bytes"
        "fmt"
        "io"
        "os/exec"
        "time"
    )

    func main() {
        cmd := exec.Command("stockfish")
        stdin, _ := cmd.StdinPipe()
        io.Copy(stdin, bytes.NewBufferString("isready\n"))
        var out bytes.Buffer
        cmd.Stdout = &out
        cmd.Start()
        time.Sleep(1000 * time.Millisecond)
        fmt.Printf(out.String())
    }
+4
source share
1 answer

You can still do this with exec.Command, and then using Cmd methods cmd.StdinPipe(), cmd.StdoutPipe()andcmd.Start()

exec.Cmd.StdoutPipe : http://golang.org/pkg/os/exec/#Cmd.StdoutPipe

. , goroutine, .

+2

Source: https://habr.com/ru/post/1527329/


All Articles