These days I have been writing a tool using golang. I have to execute external command tools and also output the logs output by external command tools. I looked online and found that there is a lot of information. The key is that the execution result is successful or the failure status is not found to obtain it.
At the beginning, I thought about it to look at the error log. If there is an error log, it will fail to execute. During the test, I found that this was not possible. I found that sometimes I used error to output the log, but it did not necessarily mean that the execution failed. Later, I wanted to use keywords in the log to match, because some commands were successfully executed or failed and the keyword output was not very good.
In the end, there was no way, I took a look()
The implementation of the method suddenly lit up, and I found the method, and there was aThe structure can be used. So I sorted out and posted the code to implement it:
func Exec(name string, args ...string) error { cmd := (name, args...) stderr, _ := () stdout, _ := () if err := (); err != nil { ("exec the cmd ", name, " failed") return err } // Normal log logScan := (stdout) go func() { for () { (()) } }() // Error log errBuf := ("") scan := (stderr) for () { s := () ("build error: ", s) (s) ("\n") } // Wait for the command to be executed () if !() { // Execution failed, return error message return (()) } return nil }
Note: The above code does not handle input, and it does not apply if the command to be executed requires input data.
Summarize
The above is the status of the golang execution command to obtain the execution result status that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!