英文:
A program that takes a command as input and runs it in the terminal
问题
我有点知道如何在C语言中实现这个,但在Go语言中如何实现呢?
以下是我使用的代码:
package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
if len(os.Args) < 2 { // 没有指定命令
fmt.Println("Usage: ./program_name terminal_command ...")
os.Exit(1)
} else {
cmd := strings.Join(os.Args[1:], " ")
cmdParts := strings.Split(cmd, " ")
cmdName := cmdParts[0]
cmdArgs := cmdParts[1:]
cmdExec := exec.Command(cmdName, cmdArgs...)
cmdExec.Stdout = os.Stdout
cmdExec.Stderr = os.Stderr
err := cmdExec.Run()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
希望对你有帮助!
英文:
I kind of know how to do this in C, but how to do it in Go?
This is the code I'm using:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CMN_LEN 100
int main(int argc, char *argv[])
{
char cmd[MAX_CMN_LEN] = "", **p;
if (argc < 2) /*no command specified*/
{
fprintf(stderr, "Usage: ./program_name terminal_command ...");
exit(EXIT_FAILURE);
}
else
{
strcat(cmd, argv[1]);
for (p = &argv[2]; *p; p++)
{
strcat(cmd, " ");
strcat(cmd, *p);
}
system(cmd);
}
return 0;
}
答案1
得分: 1
像这样:
package main
import (
"os"
"os/exec"
)
func main() {
if len(os.Args) < 2 {
panic("用法:./程序名 终端命令 ...")
}
cmd := exec.Command(os.Args[1], os.Args[2:]...)
cmd.Run()
}
英文:
Something like this:
package main
import (
"os"
"os/exec"
)
func main() {
if len(os.Args) < 2 {
panic("Usage: ./program_name terminal_command ...")
}
cmd := exec.Command(os.Args[1], os.Args[2:]...)
cmd.Run()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论