package main import ( "os/exec" "fmt" ) func main() { var( cmd *exec.Cmd output []byte err error ) cmd = exec.Command("D:\\phpStudy\\PHPTutorial\\php\\php-5.6.27-nts\\php.exe","-m") if output,err = cmd.CombinedOutput();err !=nil{ fmt.Println(err) return } fmt.Println(string(output)) }
GOROOT=D:\go #gosetup GOPATH=D:\gospace;C:\Users\Administrator\go #gosetup D:\go\bin\go.exe build -i -o C:\Users\Administrator\AppData\Local\Temp\___go_build_main_go__4_.exe D:/gospace/src/gocode/test/main.go #gosetup D:\soft\GoLand\bin\runnerw.exe C:\Users\Administrator\AppData\Local\Temp\___go_build_main_go__4_.exe #gosetup [PHP Modules] bcmath bz2 calendar Core ctype curl date dom ereg filter ftp gd hash iconv json libxml mbstring mcrypt mhash mongodb mysql mysqli mysqlnd odbc openssl pcre PDO pdo_mysql pdo_sqlite Phar Reflection session SimpleXML SPL sqlite3 standard tokenizer wddx xml xmlreader xmlwriter xsl Zend Guard Loader zip zlib [Zend Modules] Zend Guard Loader Process finished with exit code 0
window可以安装
Cygwin
package main import ( "os/exec" "fmt" ) func main() { var ( cmd *exec.Cmd output []byte err error ) // 生成Cmd cmd = exec.Command("C:\\cygwin64\\bin\\bash.exe", "-c", "D:/phpstudy/PHPTutorial/php/php-5.6.27-nts/php E:/WWW/a.php") // 执行了命令, 捕获了子进程的输出( pipe ) if output, err = cmd.CombinedOutput(); err != nil { fmt.Println(err) return } // 打印子进程的输出 fmt.Println(string(output)) }
Array ( [k1] => 1578363861 [k2] => 3c3e73f6c50c44436617869f9e978fcb )
package main import ( "os/exec" "context" "time" "fmt" ) type result struct { err error output []byte } func main() { // 执行1个cmd, 让它在一个协程里去执行, 让它执行2秒: sleep 2; echo hello; // 1秒的时候, 我们杀死cmd var ( ctx context.Context cancelFunc context.CancelFunc cmd *exec.Cmd resultChan chan *result res *result ) // 创建了一个结果队列 resultChan = make(chan *result, 1000) // context: chan byte // cancelFunc: close(chan byte) ctx, cancelFunc = context.WithCancel(context.TODO()) go func() { var ( output []byte err error ) cmd = exec.CommandContext(ctx, "C:\\cygwin64\\bin\\bash.exe", "-c", "sleep 2;echo hello;") // 执行任务, 捕获输出 output, err = cmd.CombinedOutput() // 把任务输出结果, 传给main协程 resultChan <- &result{ err: err, output: output, } }() // 继续往下走 time.Sleep(1 * time.Second) // 取消上下文 cancelFunc() // 在main协程里, 等待子协程的退出,并打印任务执行结果 res = <- resultChan // 打印任务执行结果 fmt.Println(res.err, string(res.output)) }
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/11285673.html