golang exec.Command错误no such file or directory

在使用Golang的`exec.Command`时遇到'no such file or directory'错误。问题源于`name`参数不应包含完整命令路径。解决办法是确保`name`仅包含命令名,其余参数应单独传递。在Windows上,需注意不同应用可能有不同的命令行解析算法,可能需要手动处理引号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

执行

out, err := exec.Command("grep 172.0.0.1 ~/.ssh/known_hosts | wc -l").Output()

返回RT错误

原因

exec包

func Command(name string, arg ...string) *Cmd

name参数一定要注意

If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

name不要写整条命令!!!
name不要写整条命令!!!
name不要写整条命令!!!

重要的事情说三遍

解决办法

第一个name参数是命令的名字或路径,参数一定要挨个传入

out, err := exec.Command("grep", "172.0.0.1",  "~/.ssh/known_hosts").Output()
out, err = exec.Command("wc", "-l",  "~/.ssh/known_hosts").Output()

如果是多命令,写成脚本 grep.sh

out, err := exec.Command("sh", "grep.sh").Output()

golang官宣

Command returns the Cmd struct to execute the named program with the given arguments.

It sets only the Path and Args in the returned structure.

If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

The returned Cmd’s Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command(“echo”, “hello”). Args[0] is always name, not the possibly resolved Path.

On Windows, processes receive the whole command line as a single string and do their own parsing. Command combines and quotes Args into a command line string with an algorithm compatible with applications using CommandLineToArgvW (which is the most common way). Notable exceptions are msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. In these or other similar cases, you can do the quoting yourself and provide the full command line in SysProcAttr.CmdLine, leaving Args empty.

package main

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"strings"
)

func main() {
	cmd := exec.Command("tr", "a-z", "A-Z")
	cmd.Stdin = strings.NewReader("some input")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("in all caps: %q\n", out.String())
}
package main

import (
	"log"
	"os"
	"os/exec"
)

func main() {
	cmd := exec.Command("prog")
	cmd.Env = append(os.Environ(),
		"FOO=duplicate_value", // ignored
		"FOO=actual_value",    // this value is used
	)
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

参考
https://golang.org/pkg/os/exec/#Command

引用\[1\]和\[2\]提供了两个关于在Golang中使用exec.Command函数执行外部命令的示例代码。 在Golang中,exec.Command函数用于创建一个Cmd结构体,该结构体表示要执行的外部命令。可以通过设置Cmd的属性来指定命令的输入、输出和错误流。然后,可以使用Cmd的Start方法来启动命令的执行,并使用Wait方法等待命令执行完成。 在引用\[1\]的示例中,exec.Command函数用于执行Windows命令行(cmd.exe)。通过设置Cmd的Stdin属性,可以将输入绑定到一个缓冲区,然后可以向缓冲区写入命令。通过设置Cmd的Stdout属性,可以将输出绑定到一个缓冲区,以便获取命令的输出结果。 在引用\[2\]的示例中,exec.Command函数用于执行OpenSSL命令。通过设置Cmd的Stdin、Stdout和Stderr属性,可以分别绑定输入、输出和错误流。通过调用Cmd的Start方法启动命令的执行,并使用管道读取命令的输出和错误信息。 总结来说,通过使用exec.Command函数,可以在Golang中执行外部命令,并获取其输出和错误信息。可以通过设置Cmd的属性来指定命令的输入、输出和错误流。然后,可以使用Cmd的Start方法启动命令的执行,并使用Wait方法等待命令执行完成。 #### 引用[.reference_title] - *1* [golang执行命令 exec.Command](https://blog.csdn.net/a19352226/article/details/53747323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [golang exec.Command执行cmd,jar包自定义输入与输出](https://blog.csdn.net/yoorxee/article/details/123323716)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值