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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能