io/ioutil 的问题

发布于 2025-01-12 00:39:35 字数 1256 浏览 2 评论 0原文

下午好,

我试图用我对 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 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)
}

我的主要问题是我不断遇到同一堵墙,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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睫毛上残留的泪 2025-01-19 00:39:35

我不知道在您的原始示例中什么不起作用,但是需要几分钟的实验和阅读 tasklist.exe 的文档 给了我更好的东西。主要改进是让 tasklist.exe 通过给它参数来完成繁重的工作。

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])
    }
}

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])
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文