首页 > 解决方案 > 从 cmd 输出写入文件

问题描述

我正在尝试在 Go 中编写一个小代码,该代码将从 IPFS 收集和保存统计信息。所以我的 Go 代码将执行 IPFS 命令并将其输出保存在 .txt 文件中并不断更新该 .txt 文件。我很难做到这一点。

这是我的代码:

package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "os/exec"
    "time"
)

func ipfsCommand() (ipfsOutput string) {
    // output and error
    out, err := exec.Command("ipfs","stats","bitswap","--human").Output()
    // if there are errors, print/log them
    if err != nil {
        log.Printf("error!")
        log.Fatal(err)
    } else {
        log.Printf("no error, printing output")
        fmt.Printf("%s", out)
    }
    return
}

func writeToFile(message string) error {
    f, err := os.Create("outputTest2_2.txt")
    if err != nil {
        return err
    }
    defer f.Close()
    l, err := io.WriteString(f, message)
    if err != nil {
        fmt.Println(err)
        f.Close()
        return err
    }
    fmt.Println(l, "bytes written successfully")

    return f.Sync()
}

func main() {
    // get current time
    currentTime := time.Now()
    fmt.Println("YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
    writeToFile(currentTime)
    // get output from ipfs command
    msg := ipfsCommand()
    // write the output to file
    writeToFile(msg)
    fmt.Println("file written!!!")
    
/*  // write to file many times
    for i:=0;i<3;i++{
        // get output from ipfs command
        msg := ipfsCommand()
        // write the output to file
        writeToFile(msg)
    }*/
}

当上面的代码运行时,这是错误:

# command-line-arguments
.\test2.go:49:13: cannot use currentTime (type time.Time) as type string in argument to writeToFile

同样,我想从 IPFS 获取输出并将其与当前时间一起保存到 .txt 文件中。我想循环执行此操作,因为我想长时间保存 IPFS 的输出。

标签: gofile-writingipfs

解决方案


我试图按原样修复您的脚本,但它有太多问题。这是一个重写,也许你可以把它作为一个新的起点:

package main

import (
   "os"
   "os/exec"
   "time"
)

func main() {
   f, err := os.Create("outputTest2_2.txt")
   if err != nil {
      panic(err)
   }
   defer f.Close()
   currentTime, err := time.Now().MarshalText()
   if err != nil {
      panic(err)
   }
   f.Write(append(currentTime, '\n'))
   msg, err := exec.Command("go", "env").Output()
   if err != nil {
      panic(err)
   }
   f.Write(msg)
}

推荐阅读