How to run 3rd party application from my CLI application written in Golang?

huangapple go评论82阅读模式
英文:

How to run 3rd party application from my CLI application written in Golang?

问题

我是新手,对于Golang我还不太熟悉,但幸好我有C语言的知识,所以我可以在现有的遗留代码基础上进行一些功能开发。

我有一个基于命令行界面的Go应用程序。我们还使用自定义命令与该应用程序进行交互,例如:

./my_app -s /dev/ttyACM0 -b 115200 init(通过串行接口打开应用程序)

我的问题是,我有一个第三方应用程序,我给它一些.txt文件作为输入,该应用程序会进行一些转换并输出一个文件。

我想将该应用程序的可执行文件附加到我的应用程序中,并通过我的应用程序与该应用程序进行交互,使用一个新的命令,例如:

./my_app -s /dev/ttyACM0 -b 115200 convert "my_file.txt" "生成的输出文件路径"

我需要类似的主题来给我一个起点。

英文:

I am newbie in Golang but thanks to my C-language knowledge. I could do some feature development on existing legacy code base.
I have a CLI based application written in Go. We are interacting with this app also with custom made command like :

./my_app -s /dev/ttyACM0 -b 115200 init ( opens application via Serial Interface)

My question is, I have a 3rd party application, that am giving some .txt input. This app doing some conversion and outputs a file.

I want to attach this application's executable to my application and interact with that application over my own application with the help of a new command like

./my_app -s /dev/ttyACM0 -b 115200 convert "./my_file.txt" "output path file to be generate"

I need similar topic may give me a starting point.

答案1

得分: 2

go/exec 包处理外部命令的执行。要执行给定的命令,你可以编写如下代码:

package main

import (
    "log"
	"os/exec"
)

func main() {
	cmd := exec.Command("./my_third_party_executable", "-s", "/dev/ttyACM0", "-b", "115200", "convert", "./my_file.txt", "output path file to be generate")
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}
英文:

The go/exec package handles the execution of external commands. To execute your given command you could write code like this:

package main

import (
    "log"
	"os/exec"
)

func main() {
	cmd := exec.Command("./my_third_party_executable", "-s", "/dev/ttyACM0", "-b", "115200", "convert" "./my_file.txt", "output path file to be generate")
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}

huangapple
  • 本文由 发表于 2023年2月22日 21:28:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75533381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定