Exec a shell command in Go

前端 未结 7 1616
甜味超标
甜味超标 2020-12-04 10:01

I\'m looking to execute a shell command in Go and get the resulting output as a string in my program. I saw the Rosetta Code version:

package main
import \"f         


        
7条回答
  •  心在旅途
    2020-12-04 10:37

    I did not get the Rosetta example to work in my Windows Go. Finally I managed to go past the old format of the Subprocess with this command to start outfile in notepad in windows. The wait constant parameter mentioned in one manual did not exist so I just left out Wait as the user will close the program by themself or leave it open to reuse.

    p, err := os.StartProcess(`c:\windows\system32\notepad.EXE`,
        []string{`c:\windows\system32\notepad.EXE`, outfile},
        &os.ProcAttr{Env: nil, Dir: "", Files:  []*os.File{os.Stdin, os.Stdout, os.Stderr}})
    

    You would change the os.Stdout.. to os.Pipe as previous answer

    EDIT: I got it finally from godoc os Wait, that Wait has changed to method of and I succeeded to do:

       defer p.Wait(0)
    

    Then I decided finally to put

       defer p.Release()
    

    instead.

提交回复
热议问题