简体   繁体   English

如何执行我的程序创建的文件?

[英]How to execute file created by my program?

I'm trying to execute .ics file that my program just created.我正在尝试执行我的程序刚刚创建的.ics文件。 Basically, my program is simple CLI calendar app, which generates.ics file.基本上,我的程序是简单的 CLI 日历应用程序,它生成 .ics 文件。 It would be nice if my program would execute this file and add it straight to OS calendar app, without unnecessary searching and executing through OS GUI.如果我的程序能够执行此文件并将其直接添加到 OS 日历应用程序,而不需要通过 OS GUI 进行不必要的搜索和执行,那就太好了。 I paste main function to better understanding.我粘贴主要的 function 以便更好地理解。

func main() {

    serialized, name := cal()

    f, err := os.Create(name + ".ics")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    _, err2 := f.WriteString(serialized)
    if err2 != nil {
        log.Fatal(err2)
    }
    cmd := exec.Command(name + ".ics")
    err = cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

As it's shown I tried with exec.Command , but it doesnt' work.如图所示,我尝试使用exec.Command ,但它不起作用。 I was even trying with additional prefixes like ./ or ~/ , but it as well worked.我什至尝试使用额外的前缀,如./~/ ,但效果也很好。

Error messages:错误信息:

fork/exec./Meeting.ics: permission denied

exec: "Meeting.ics": executable file not found in $PATH

So to sum it up - I want to skip the process where the user has to find a file and open it.所以总结一下 - 我想跳过用户必须找到文件并打开它的过程。 I want to make it automatically as a part of my application.我想让它自动成为我应用程序的一部分。

Here's my repository if it would help https://github.com/lenoopaleno/golang-calendar这是我的存储库,如果它可以帮助https://github.com/lenoopaleno/golang-calendar

I'm working on WSL 2, Ubuntu 22.04我正在研究 WSL 2,Ubuntu 22.04

Beside the comments above, you might have a problem in your code with the defer f.Close()除了上面的注释之外,您的代码中的defer f.Close()可能存在问题

The defer runs when the function ends.当 function 结束时,延迟运行。 Until that time your file might or might not be closed and accessible by a different process.在此之前,您的文件可能会或可能不会被其他进程关闭和访问。 Second you will most likely have to set an execute flag on the a program to run under unix style operating systems.其次,您很可能必须在程序上设置一个执行标志才能在 unix 风格的操作系统下运行。

Program adjustment:节目调整:

func main() {

    serialized, name := cal()

    f, err := os.Create(name + ".ics")
    if err != nil {
        log.Fatal(err)
    }

    _, err2 := f.WriteString(serialized)
    if err2 != nil {
        log.Fatal(err2)
    }
    f.Sync()
    f.Close()
    exec.Command(`chmod +x `+name+".ics").Run() // This can be done prettier
    cmd := exec.Command(name + ".ics")
    err = cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM