Search code examples
shellgoprocessgraphviz

How to run a graphviz process with a dot script from a Go program?


I want to run a dot script that outputs to an image.
How do I call it from Golang?

package main

import (
"fmt"

"os/exec"
)

func main() {
path, err := exec.LookPath("dot")
cmd := exec.Command(path, "-Tpng", "/Users/arafat/Desktop/dev/go/src/github.com/Arafatk/dataviz/DotExamples/arraylist.dot", ">", "/Users/arafat/Desktop/dev/go/src/github.com/Arafatk/dataviz/hello.png")
err = cmd.Run()

fmt.Println(path)
if err != nil {
    println(err.Error())
    return
}
}

This is my code which gives exit code 3.

@zerkms
Sorry, I can do that I am just confused because this code does not give any output except nil.

path, _ := exec.LookPath("dot")       
cmd := exec.Command(path, "-Tpng", "/Users/arafat/Desktop/dev/go/src/github.com/Arafatk/dataviz/DotExamples/arraylist.dot")        
out := cmd.Run()       
fmt.Println(out)         

But this command line function works

dot -Tpng  /Users/arafat/Desktop/dev/go/src/github.com/Arafatk/dataviz/DotExamples/arraylist.dot           

Can you tell me how to actually use the function above in Golang?


Solution

  • As mentioned before by @zerkms you can use cmd.StdoutPipe() instead of ">".
    However there is a much simpler way to solve this problem

    package main
    
    import (
       "io/ioutil"
       "os"
       "os/exec"
    )
    
    func main() {
    path, _ := exec.LookPath("dot")
    cmd, _ := exec.Command(path, "-Tpng", "/Users/arafat/Desktop/dev/go/src/github.com/Arafatk/dataviz/DotExamples/arraylist.dot").Output()
    mode := int(0777)
       ioutil.WriteFile("outfile.png", cmd, os.FileMode(mode))
    }