go - 从 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 的输出。
解决方案
我试图按原样修复您的脚本,但它有太多问题。这是一个重写,也许你可以把它作为一个新的起点:
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)
}
推荐阅读
- php - 如何解决 AddRemarkRQ 的错误 EbxmlMessage?
- arm - ARM Cortex-A8 L2 缓存未命中开销
- ansible - Vagrantfile:语法错误,意外的输入结束,期待keyword_end
- tcl - 需要帮助使用期望从不断变化的日志文件中提取特定行
- python-3.x - 导入的类可以使用导入文件中的函数和类吗?
- python - 在 Python3 中不使用 writelines() 将多行写入文件
- c# - 领域驱动设计模型:客户服务案例,更非规范化,扁平化?
- macos - 有没有办法将 AppleScript 的输出设置为某种颜色,并根据条件进行更改?
- html - 需要帮助构建音量滑块
- c++ - `auto o = SomeType(args)` 而不是 `SomeType o(args)` 是否存在潜在的性能损失?