如何解决从 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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。