如何运行一个简单的Windows 命令?
这个命令:
exec.Command("del", "c:\\aaa.txt")
.. 输出此消息:
del: 在 %path% 中找不到可执行文件
我究竟做错了什么?
我得到了和你一样的错误。但是dystroy是正确的:您无法运行del
或内置任何其他命令,cmd
因为没有del.exe
文件(或任何其他del-executable)。
我得到了它的工作:
package main
import(
"fmt"
"os/exec"
)
func main(){
c := exec.Command("cmd", "/C", "del", "D:\\a.txt")
if err := c.Run(); err != nil {
fmt.Println("Error: ", err)
}
}
您需要一个 Windows cmd 来执行您的dir
命令。
试试这个 :
cmd := exec.Command("cmd", "/C", "dir").Output()
(抱歉,目前没有 Windows 计算机可以检查)
也找到了另一个解决方案。创建一个包含以下内容的批处理文件:del c:\aaa.txt
然后像这样调用它:
exec.Command("c:\\del.bat").Run()
如果您需要 cmd 的输出:
if c, err := exec.Command("cmd","/c","del","a.txt").CombinedOutput(); err != nil {
log.Fatal(err)
} else {
fmt.Printf("%s\n", c)
}
好的,让我们看看,根据文档,在 Windows 中,进程以单行字符串的形式接收命令并自己进行一些解析。Exec 的 Command 函数通过使用 CommandLineToArgvW 将所有参数组合在一起来构建命令字符串,尽管它是最常见的引用算法,但并不适用于每个应用程序。msiexec.exe 和 cmd.exe 等应用程序使用不兼容的取消引用算法,因此需要额外的努力。这是使用 powershell 的不同示例
package main
import (
"os/exec"
"fmt"
"log"
)
func main() {
out, err := exec.Command("powershell","remove-item","aaa.txt").Output()
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("%s",out)
}
您可以尝试使用 github.com/go-cmd/cmd 模块。
因为 golang 默认不能使用 syscall。
例子:
import (
"fmt"
"time"
"github.com/go-cmd/cmd"
)
func main() {
// Start a long-running process, capture stdout and stderr
findCmd := cmd.NewCmd("find", "/", "--name", "needle")
statusChan := findCmd.Start() // non-blocking
ticker := time.NewTicker(2 * time.Second)
// Print last line of stdout every 2s
go func() {
for range ticker.C {
status := findCmd.Status()
n := len(status.Stdout)
fmt.Println(status.Stdout[n-1])
}
}()
// Stop command after 1 hour
go func() {
<-time.After(1 * time.Hour)
findCmd.Stop()
}()
// Check if command is done
select {
case finalStatus := <-statusChan:
// done
default:
// no, still running
}
// Block waiting for command to exit, be stopped, or be killed
finalStatus := <-statusChan
}