Issues with io/ioutil

huangapple go评论88阅读模式
英文:

Issues with io/ioutil

问题

下午好,

根据我有限的golang知识,我尝试获取进程ID,并且以下是我想出的代码:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
)

func main() {
	cmd := exec.Command("tasklist.exe")
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatal(err)
	}
	f, err := os.Create("data.txt")

	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	val := out
	data := []byte(val)

	_, err2 := f.Write(data)

	if err2 != nil {
		log.Fatal(err2)
	}

	val2 := " and red fox\n"
	data2 := []byte(val2)

	var idx int64 = int64(len(data))

	_, err3 := f.WriteAt(data2, idx)

	if err3 != nil {
		log.Fatal(err3)
	}

	fmt.Println("done")
	/* ioutil.ReadFile返回[]byte和错误 */
	explorer, err := ioutil.ReadFile("data.txt")
	/* ...省略错误检查...请添加... */
	/* 找到换行符的索引 */
	file := string(data)
	line := 0
	/* func Split(s, sep string) []string */
	temp := strings.Split(file, "\n")

	for _, item := range temp {
		fmt.Println("[", line, "]\t", item)
		line++
	}
	fmt.Println(explorer)
}

我的主要问题是,我一直遇到同样的问题,即ioutil不允许我在读取文件之前赋值。

有人能帮我解决这个问题吗?

英文:

Good afternoon,

I'm trying to grab processes id's with my limited knowledge on golang and the below is what I've come up with:

    package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
)
func main() {
cmd := exec.Command("tasklist.exe")
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatal(err)
}
f, err := os.Create("data.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
val := out
data := []byte(val)
_, err2 := f.Write(data)
if err2 != nil {
log.Fatal(err2)
}
val2 := " and red fox\n"
data2 := []byte(val2)
var idx int64 = int64(len(data))
_, err3 := f.WriteAt(data2, idx)
if err3 != nil {
log.Fatal(err3)
}
fmt.Println("done")
/* ioutil.ReadFile returns []byte, error */
explorer, err := ioutil.ReadFile("data.txt")
/* ... omitted error check..and please add ... */
/* find index of newline */
file := string(data)
line := 0
/* func Split(s, sep string) []string */
temp := strings.Split(file, "\n")
for _, item := range temp {
fmt.Println("[", line, "]\t", item)
line++
}
fmt.Println(explorer)
}

My Main issue is that i keep running into the same wall where ioutil won't let me assign a value before reading the file.

Is anyone able to help me out here?

答案1

得分: 0

我不知道你原始示例中有什么问题,但是经过几分钟的实验和阅读 tasklist.exe 的文档,我得到了一个更好的解决方案。主要的改进是通过给 tasklist.exe 提供参数来让它完成繁重的工作。

package main

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"log"
	"os/exec"
)

func main() {
	// 原始命令:
	// tasklist.exe /nh /fo csv /fi "IMAGENAME eq explorer.exe"
	// /nh = 不显示标题
	// /fo csv = 输出格式为 csv
	// /fi = 过滤查询
	//
	// 运行 tasklist.exe /? 以获取更多信息
	//
	// 示例输出:
	// "explorer.exe","4860","Console","1","102,240 K"

	// 使用参数启动 tasklist 来为我们完成繁重的工作。
	// 我们希望得到 CSV 格式的输出(更容易解析),并让 tasklist 搜索 explorer.exe。
	// 当然,你也可以搜索其他任务名称而不是 explorer.exe。
	//
	// 这里的关键是查询("IMAGENAME ...")在传递给 exec.Command() 时不需要使用引号,
	// 因为 exec.Command() 似乎会为你处理这个问题
	// (像 `"IMAGENAME..."` 这样的引号会导致 Output() 出错)
	cmd := exec.Command("tasklist.exe", "/nh", "/fo", "csv", "/fi", "IMAGENAME eq explorer.exe")
	out, err := cmd.Output()
	if err != nil {
		log.Fatalln(err)
	}

	// 创建一个围绕上述命令输出的 csv 读取器。
	// 然后使用 ReadAll() 将 csv 拆分为 [][]string,即每行是一个切片
	// 的“行”(也称为记录、行),其中每行是 csv 的“列”(也称为字段、条目)的切片。
	r := csv.NewReader(bytes.NewReader(out))
	lines, err := r.ReadAll()
	if err != nil {
		log.Fatalln(err)
	}

	// 结果可能有多个进程(例如 svchost.exe)或没有进程。
	for _, line := range lines {
		// 进程 ID 作为字符串位于索引 1 处。
		// 根据需要处理结果。
		fmt.Println(line[1])
	}
}

以上是你要翻译的内容。

英文:

I don't know what's not working in your original example, but a few minutes of experimentation and reading the docs for tasklist.exe gave me something better. The main improvement is letting tasklist.exe do the heavy lifting by giving it args.

package main

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"log"
	"os/exec"
)

func main() {
	// original command:
	// tasklist.exe /nh /fo csv /fi "IMAGENAME eq explorer.exe"
	// /nh = no header
	// /fo csv = format output to csv
	// /fi = filter on query
	//
	// run tasklist.exe /? for more info
	//
	// sample output:
	// "explorer.exe","4860","Console","1","102,240 K"

	// start tasklist with args to do the hard work for us.
	// we want CSV output (easier to parse), and let tasklist search for explorer.exe.
	// obviously you could seach for another task name instead of explorer.exe.
    //
    // the key thing here is that the query ("IMAGENAME ...") doesn't
    // require " when passed as an arg because exec.Command()
    // will apparently handle that for you 
    // (quoting like `"IMAGENAME..."` produced an error from Output() )
	cmd := exec.Command("tasklist.exe", "/nh", "/fo", "csv", "/fi", "IMAGENAME eq explorer.exe")
	out, err := cmd.Output()
	if err != nil {
		log.Fatalln(err)
	}

	// create a csv reader around the output of the above command.
	// then use ReadAll() to split the csv into [][]string.. a slice
	// of "lines" (aka records, rows) where each line is a slice of 
    // csv "columns" (aka fields, entries).
	r := csv.NewReader(bytes.NewReader(out))
	lines, err := r.ReadAll()
	if err != nil {
		log.Fatalln(err)
	}

	// the result may have multiple processes (eg svchost.exe) or none.
	for _, line := range lines {
		// the process id is at index 1 as a string.
		// do whatever you need to do with the result.
		fmt.Println(line[1])
	}
}

huangapple
  • 本文由 发表于 2022年3月6日 09:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/71367186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定