用CMD打开chrome并导航到百度(golang)
首选在cmd中输入(注意:根据你的电脑路径修改,可能是Progra~1):
C:\Progra~2\Google\Chrome\Application\chrome.exe www.baidu.com
可以成功打开浏览器并导航到百度。
golang 代码如下:
package main import ( "bytes" "fmt" "log" "os/exec" ) var err error func main() { cmd := exec.Command("cmd") in := bytes.NewBuffer(nil) cmd.Stdin = in //绑定输入 var out bytes.Buffer cmd.Stdout = &out //绑定输出 go func() { in.WriteString("start C:\\Progra~2\\Google\\Chrome\\Application\\chrome.exe www.baidu.com\n") //写入你的命令,可以有多行,"\n"表示回车 }() err = cmd.Start() if err != nil { log.Fatal(err) } log.Println(cmd.Args) err = cmd.Wait() if err != nil { log.Printf("Command finished with error: %v", err) } fmt.Println(out.String()) }
更简单的办法是在main中写一句:
exec.Command("cmd", "/c", "C:\\Progra~2\\Google\\Chrome\\Application\\chrome.exe", "www.baidu.com").Run()
参考:
https://blog.csdn.net/a19352226/article/details/53747323
https://blog.csdn.net/soaringlee_fighting/article/details/70473817
packagemain
import(
"bytes"
"fmt"
"log"
"os/exec"
)
varerrerror
funcmain(){
cmd:=exec.Command("cmd")
in:=bytes.NewBuffer(nil)
cmd.Stdin=in//绑定输入
varoutbytes.Buffer
cmd.Stdout=&out//绑定输出
gofunc(){
in.WriteString("startC:\\Progra~2\\Google\\Chrome\\Application\\chrome.exewww.baidu.com\n")//写入你的命令,可以有多行,"\n"表示回车
}()
err=cmd.Start()
iferr!=nil{
log.Fatal(err)
}
log.Println(cmd.Args)
err=cmd.Wait()
iferr!=nil{
log.Printf("Commandfinishedwitherror:%v",err)
}
fmt.Println(out.String())
}