一个接受命令作为输入并在终端中运行的程序

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

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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

#define MAX_CMN_LEN 100

int main(int argc, char *argv[])
{
    char cmd[MAX_CMN_LEN] = &quot;&quot;, **p;

    if (argc &lt; 2) /*no command specified*/
    {
        fprintf(stderr, &quot;Usage: ./program_name terminal_command ...&quot;);
        exit(EXIT_FAILURE);
    }
    else
    {
        strcat(cmd, argv[1]);
        for (p = &amp;argv[2]; *p; p++)
        {
            strcat(cmd, &quot; &quot;);
            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 (
    &quot;os&quot;
    &quot;os/exec&quot;
)

func main() {
    if len(os.Args) &lt; 2 {
        panic(&quot;Usage: ./program_name terminal_command ...&quot;)
    }
    
    cmd := exec.Command(os.Args[1], os.Args[2:]...)
    cmd.Run()
}

huangapple
  • 本文由 发表于 2017年4月9日 21:51:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/43307491.html
匿名

发表评论

匿名网友

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

确定