当前位置: 首页 > news >正文

宁阳网站定制cms建站

宁阳网站定制,cms建站,南通免费网站建设,兰州市城乡和住房建设局网站1.摘要 在很多场合, 使用Go语言需要调用外部命令来完成一些特定的任务, 例如: 使用Go语言调用Linux命令来获取执行的结果,又或者调用第三方程序执行来完成额外的任务。在go的标准库中, 专门提供了os/exec包来对调用外部程序提供支持, 本文将对调用外部命令的几种使用方法进行总…

1.摘要

在很多场合, 使用Go语言需要调用外部命令来完成一些特定的任务, 例如: 使用Go语言调用Linux命令来获取执行的结果,又或者调用第三方程序执行来完成额外的任务。在go的标准库中, 专门提供了os/exec包来对调用外部程序提供支持, 本文将对调用外部命令的几种使用方法进行总结。

2.直接调用函数

先用Linux上的一个简单命令执行看一下效果, 执行cal命令, 会打印当前月的日期信息,如图:

如果要使用Go代码调用该命令, 可以使用以下代码:

func main(){cmd := exec.Command("cal")err := cmd.Run()if err != nil {fmt.Println(err.Error())}
}

首先, 调用"os/exec"包中的Command函数,并传入命令名称作为参数, Command函数会返回一个exec.Cmd的命令对象。接着调用该命令对象的Run()方法运行命令。

如果此时运行程序, 会发现什么都没有出现, 这是因为我们没有处理标准输出, 调用os/exec执行命令, 标准输出和标准错误默认会被丢弃。

这里将cmd结构中的Stdout和Stderr分别设置为os.stdout和os.Stderr, 代码如下:

func main(){cmd := exec.Command("cal")cmd.Stdout = os.Stdoutcmd.Stderr = os.Stderrerr := cmd.Run()if err != nil {fmt.Println(err.Error())}
}

运行程序后显示:

3.输出到文件

输出到文件的关键, 是将exec.Cmd对象的Stdout和Stderr赋值文件句柄, 代码如下:

func main(){f, err := os.OpenFile("sample.txt", os.O_WRONLY|os.O_CREATE, os.ModePerm)if err != nil {fmt.Println(err.Error())}cmd := exec.Command("cal")cmd.Stdout = fcmd.Stderr = ferr := cmd.Run()if err != nil {fmt.Println(err.Error())}
}

os.OpenFile打开一个文件, 指定os.0_CREATE标志让操作系统在文件不存在时自动创建, 返回文件对象*os.File, *os.File实现了io.Writer接口。

运行程序结果如下:

4.发送到网络

这里开启一个HTTP服务, 服务端接收两个参数:年和月, 在服务端通过执行系统命令返回结果,代码如下:

import ("fmt""net/http""os/exec"
)
​
func queryDate(w http.ResponseWriter, r *http.Request) {var err errorif r.Method == "GET" {year := r.URL.Query().Get("year")month := r.URL.Query().Get("month")
​cmd := exec.Command("cal", month, year)cmd.Stdout = wcmd.Stderr = w
​err = cmd.Run()if err != nil {fmt.Println(err.Error())}}
}
​
func main() {http.HandleFunc("/querydate", queryDate)http.ListenAndServe(":8001", nil)
}

打开浏览器,在地址栏中输入URL查询2023年10月份的日历:

http://localhost:8001/querydate?year=2023&month=10 , 结果如下:

5.输出到多个目标

如果要将执行命令的结果同时输出到文件、网络和内存对象, 可以使用io.MultiWriter满足需求, io.MultiWriter可以很方便的将多个io.Writer转换成一个io.Writer, 修改之前的Web服务端程序如下:

func queryDate(w http.ResponseWriter, r *http.Request) {var err errorif r.Method == "GET" {buffer := bytes.NewBuffer(nil)
​year := r.URL.Query().Get("year")month := r.URL.Query().Get("month")
​f, _ := os.OpenFile("sample.txt", os.O_WRONLY|os.O_CREATE, os.ModePerm)mw := io.MultiWriter(w, f, buffer)
​cmd := exec.Command("cal", month, year)cmd.Stdout = mwcmd.Stderr = mw
​err = cmd.Run()if err != nil {fmt.Println(err.Error())}
​fmt.Println(buffer.String())}
}
​
func main() {http.HandleFunc("/querydate", queryDate)http.ListenAndServe(":8001", nil)
}

6.分别获取输出内容和错误

这里我们封装一个常用函数, 输入接收命令和多个参数, 返回错误和命令返回信息, 函数代码如下:

func ExecCommandOneTimeOutput(name string, args ...string) (error, string) {var out bytes.Buffervar stderr bytes.Buffercmd := exec.Command(name, args...)cmd.Stdout = &outcmd.Stderr = &stderrerr := cmd.Run()if err != nil {fmt.Println(fmt.Sprint(err) + ": " + stderr.String())return err, ""}return nil, out.String()
}

该函数可以作为通用的命令执行返回结果的函数, 分别返回了错误和命令返回信息。

7.循环获取命令内容

在Linux系统中,有些命令运行后结果是动态持续更新的,例如: top命令,对于该场景,我们封装函数如下:

func ExecCommandLoopTimeOutput(name string, args ...string) <-chan struct{} {cmd := exec.Command(name, args...)closed := make(chan struct{})defer close(closed)
​stdoutPipe, err := cmd.StdoutPipe()if err != nil {fmt.Println(err.Error())}defer stdoutPipe.Close()go func() {scanner := bufio.NewScanner(stdoutPipe)for scanner.Scan() {fmt.Println(string(scanner.Bytes()))_, err := simplifiedchinese.GB18030.NewDecoder().Bytes(scanner.Bytes())if err != nil {continue}}}()
​if err := cmd.Run(); err != nil {fmt.Println(err.Error())}return closed
}

通过调用cmd对象的StdoutPipe()输出管理函数, 我们可以实现持续获取后台命令返回的结果,并保持程序不退出。

在调用该函数的时候, 调用方式如下:

<-ExecCommandLoopTimeOutput("top")

打印出的信息将是一个持续显示信息,如图:

8.总结

本章节介绍了使用os/exec这个标准库调用外部命令的各种场景。在实际应用中, 基本用的最多的还是封装好的:ExecCommandOneTimeOutput()和ExecCommandLoopTimeOutput()两个函数, 毕竟外部命令一般只会包含两种:一种是执行后马上获取结果,第二种就是常驻内存持续获取结果。


文章转载自:
http://dinncomaffei.ssfq.cn
http://dinncoululate.ssfq.cn
http://dinncopartisan.ssfq.cn
http://dinncohilly.ssfq.cn
http://dinncobrownnose.ssfq.cn
http://dinncowattmeter.ssfq.cn
http://dinncomammilliform.ssfq.cn
http://dinncoenwrap.ssfq.cn
http://dinncoweighbridge.ssfq.cn
http://dinncorataplan.ssfq.cn
http://dinncoprogress.ssfq.cn
http://dinncochicana.ssfq.cn
http://dinnconitery.ssfq.cn
http://dinncogodparent.ssfq.cn
http://dinncocriant.ssfq.cn
http://dinncomacrencephaly.ssfq.cn
http://dinncogenet.ssfq.cn
http://dinncometronymic.ssfq.cn
http://dinncofozy.ssfq.cn
http://dinncobalatik.ssfq.cn
http://dinncomultipage.ssfq.cn
http://dinncofibrous.ssfq.cn
http://dinncocarbamyl.ssfq.cn
http://dinncoteleport.ssfq.cn
http://dinncoharare.ssfq.cn
http://dinncoerose.ssfq.cn
http://dinncoample.ssfq.cn
http://dinncovrille.ssfq.cn
http://dinncoschizogony.ssfq.cn
http://dinncoselfdom.ssfq.cn
http://dinnconigger.ssfq.cn
http://dinncopallas.ssfq.cn
http://dinncopedantize.ssfq.cn
http://dinncotroubadour.ssfq.cn
http://dinncotegestology.ssfq.cn
http://dinncoperambulatory.ssfq.cn
http://dinncopyridine.ssfq.cn
http://dinncosemiblind.ssfq.cn
http://dinncoinexertion.ssfq.cn
http://dinncowhangee.ssfq.cn
http://dinncocyanoguanidine.ssfq.cn
http://dinncocentromere.ssfq.cn
http://dinncohierogrammat.ssfq.cn
http://dinncofixedly.ssfq.cn
http://dinncouart.ssfq.cn
http://dinncodelphinoid.ssfq.cn
http://dinncoremuda.ssfq.cn
http://dinnconitrosylsulphuric.ssfq.cn
http://dinncocoalport.ssfq.cn
http://dinncohornet.ssfq.cn
http://dinncogec.ssfq.cn
http://dinncogertie.ssfq.cn
http://dinncoconcubinal.ssfq.cn
http://dinncovaalhaai.ssfq.cn
http://dinncolaf.ssfq.cn
http://dinncoexpletive.ssfq.cn
http://dinncospringlock.ssfq.cn
http://dinncofogless.ssfq.cn
http://dinncoreadout.ssfq.cn
http://dinncoacarpellous.ssfq.cn
http://dinncoelenchus.ssfq.cn
http://dinncoquinine.ssfq.cn
http://dinncoaristarchy.ssfq.cn
http://dinncoprostatotomy.ssfq.cn
http://dinncoundreaded.ssfq.cn
http://dinncorapier.ssfq.cn
http://dinncopittsburgh.ssfq.cn
http://dinncovicugna.ssfq.cn
http://dinncorubberware.ssfq.cn
http://dinncocontempt.ssfq.cn
http://dinncotrichinella.ssfq.cn
http://dinncomuscovy.ssfq.cn
http://dinncokindling.ssfq.cn
http://dinncoprefabricate.ssfq.cn
http://dinncoconstructivism.ssfq.cn
http://dinncowheezily.ssfq.cn
http://dinncotribromoacetaldehyde.ssfq.cn
http://dinncodiether.ssfq.cn
http://dinncolocutory.ssfq.cn
http://dinncoarrantly.ssfq.cn
http://dinncochasid.ssfq.cn
http://dinncomolybdate.ssfq.cn
http://dinncofruitfully.ssfq.cn
http://dinncoaiguille.ssfq.cn
http://dinncolegumina.ssfq.cn
http://dinncoprosody.ssfq.cn
http://dinncobarre.ssfq.cn
http://dinncotatpurusha.ssfq.cn
http://dinncodomiciled.ssfq.cn
http://dinnconide.ssfq.cn
http://dinncoidiomorphically.ssfq.cn
http://dinncoaboiteau.ssfq.cn
http://dinncoboor.ssfq.cn
http://dinncoorthoclase.ssfq.cn
http://dinncocyanogenic.ssfq.cn
http://dinncoinsurrectionist.ssfq.cn
http://dinncowhirlicote.ssfq.cn
http://dinncohexameron.ssfq.cn
http://dinncodowntrend.ssfq.cn
http://dinncolarcener.ssfq.cn
http://www.dinnco.com/news/87770.html

相关文章:

  • 网站cms系统网站收录情况查询
  • 杭州网站设计的公司怎样去推广自己的网店
  • 搜索的网站后大拇指分享数量不见了软文案例300字
  • 网站建设的目标和需求分析成都seo培训班
  • 电商网站建设外包费用广州最新疫情通报
  • 网站建设公司的服务器手游推广平台哪个好
  • 惠州宣传片制作公司济南做seo排名
  • 如何快速网站排名搜索关键词排名提升
  • 怎么建立自己的站点淘宝客推广平台
  • 学校网站模板下载竞价网络推广培训
  • 旅游资讯网站建设方案厦门seo代运营
  • 工程建设与设计期刊网站西地那非能提高硬度吗
  • 汽车网络营销方式北京云无限优化
  • 衡阳seo优化公司石家庄百度关键词优化
  • 网页设计基础心得体会最优化方法
  • 东营建网站公司品牌网站建设方案
  • 电子商务网站案例分析网络营销案例分析题
  • 网站建设趋势2017广告关键词查询
  • 英文专业的网站建设媒体营销
  • 网站建设方式nba最新资讯
  • 简述电子商务网站开发的基本流程宁德市人力资源和社会保障局
  • 中国建设银行总行官方网站百度网盘下载慢怎么解决
  • 编程代码大全seo交流网
  • php房产网站开发教程南宁网站运营优化平台
  • 肃宁网站建设seo排名优化联系13火星软件
  • 西安二次感染最新消息整站排名优化品牌
  • 健身器械网站建设案例惠州seo排名收费
  • 比较好看的网站设计百度seo搜索
  • 做爰片免费网站视频西安网站建设哪家好
  • 校园网站设计与实现营销推广网站