登录
首页 >  Golang >  Go问答

Mac 上终端与 IDE 中运行 Golang 应用程序的不同

来源:stackoverflow

时间:2024-03-07 17:45:25 388浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《Mac 上终端与 IDE 中运行 Golang 应用程序的不同》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我想使用golang语言对我的mac桌面进行截图。有一个很好用且简单的工具:https://github.com/kbinani/screenshot 我已经使用它有一段时间了,但最近我尝试再次使用它,并注意到我的两台 macbook(big sur 和 catalina)上出现了奇怪的行为。

这是一个简单的代码:

package main

import (
    "fmt"
    "github.com/kbinani/screenshot"
    "image/png"
    "os"
)

func main(){
    bounds := screenshot.getdisplaybounds(0)

    img, err := screenshot.capturerect(bounds)
    if err != nil {
        panic(err)
    }
    filename := fmt.sprintf("%d_%dx%d.png", 0, bounds.dx(), bounds.dy())
    file, _ := os.create(filename)
    defer file.close()
    png.encode(file, img)

    fmt.printf("#%d : %v \"%s\"\n", 0, bounds, filename)
}

上面的代码应该捕获第一个屏幕并将文件保存为接近二进制的“0_2560x1440.png”。 当我从 jetbrains goland ide 运行二进制文件或使用 在 jetbrains goland ide 终端内执行 go run main.go 命令一切正常。但是,如果我从默认终端(或 iterm)运行二进制文件或go run main.go,我将收到没有任何窗口的屏幕截图,只是一个没有任何 winodws 或foldres 的普通桌面。

这是什么原因呢?从 ide 终端或 os 终端运行二进制文件有什么区别?

经过一番考虑,我认为可能是 golang 截图库中的某个地方存在错误。我尝试使用 osx api 运行另一个代码:

package main

// To use the two libraries we need to define the respective flags, include the required header files and import "C" immediately after
import (
    // #cgo LDFLAGS: -framework CoreGraphics
    // #cgo LDFLAGS: -framework CoreFoundation
    // #include 
    // #include 
    "C"
    "image"
    "image/png"
    "os"
    "reflect"
    "unsafe"
    // other packages...
)

func main() {
    displayID := C.CGMainDisplayID()
    width := int(C.CGDisplayPixelsWide(displayID))
    height := int(C.CGDisplayPixelsHigh(displayID))
    rawData := C.CGDataProviderCopyData(C.CGImageGetDataProvider(C.CGDisplayCreateImage(displayID)))

    length := int(C.CFDataGetLength(rawData))
    ptr := unsafe.Pointer(C.CFDataGetBytePtr(rawData))

    var slice []byte
    hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&slice))
    hdrp.Data = uintptr(ptr)
    hdrp.Len = length
    hdrp.Cap = length

    imageBytes := make([]byte, length)

    for i := 0; i < length; i += 4 {
        imageBytes[i], imageBytes[i+2], imageBytes[i+1], imageBytes[i+3] = slice[i+2], slice[i], slice[i+1], slice[i+3]
    }

    //C.CFRelease(rawData)

    img := &image.RGBA{Pix: imageBytes, Stride: 4 * width, Rect: image.Rect(0, 0, width, height)}
    // There we go, we can now save or process the image further

    file, err := os.Create("file.png")
    if err != nil {
        panic(err)
    }
    defer file.Close()
    if err := png.Encode(file, img); err != nil {
        panic(err)
    }
}

这段代码给出了相同的结果。在 ide 终端中运行 - 正常行为。在其他地方运行 - 屏幕截图现在有内容。

请帮我揭开这个谜团。


解决方案


经过一番调查后发现问题只是 OSX 权限问题。有录屏权限。 IDE 允许,但终端不允许。

没有弹出窗口或类似的东西。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>