无法在 Go Lambda 中访问文件系统。

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

Can't access filesystem in Go Lambda

问题

我之前使用过Lambda函数,如果我没记错的话,我应该有大约500MB的(临时)空间在/tmp目录下。

然而,我的Go Lambda函数似乎无法正确地与文件系统进行交互:

exec.Command("ls -la /").Output() 返回空值

exec.Command("rm -rf /tmp/xxx").Run() 返回 fork/exec: 没有那个文件或目录

exec.Command("mkdir -p /tmp/xxx").Run() 返回 fork/exec: 没有那个文件或目录

这真的很奇怪。
它正在使用go1.x环境(因此,我猜是amazonlinux:2)。

更新

我可以使用Go的os函数访问文件系统:

os.RemoveAll("/tmp/xxx")

if _, err := os.Stat("/tmp/xxx"); os.IsNotExist(err) {
	if err := os.Mkdir("/tmp/xxx", os.ModePerm); err != nil {
		return err
	}
}

但是我真的需要使用exec来运行之后的二进制命令,并在那个tmp文件夹中写入文件。在这种情况下,错误是相同的(没有那个文件或目录)。尽管我刚刚用上述命令创建了文件夹。

英文:

I used Lambda functions before, and if I remember correctly I'm supposed to have ~500Mb of (ephemeral) space in /tmp.

Nevertheless, my Go lambda function doesn't seem to interact with the fs properly:

exec.Command("ls -la /").Output() returns empty

exec.Command("rm -rf /tmp/xxx").Run() returns fork/exec : no such file or directory

exec.Command("mkdir -p /tmp/xxx").Run() returns fork/exec : no such file or directory

It's really weird.
It's using the go1.x environment (thus, I guess amazonlinux:2)

UPDATE

I CAN access the fs using Go os functions:

os.RemoveAll("/tmp/xxx")

if _, err := os.Stat("/tmp/xxx"); os.IsNotExist(err) {
	if err := os.Mkdir("/tmp/xxx", os.ModePerm); err != nil {
		return err
	}
}

BUT I really need exec to run afterwards (a binary command), and write a file in that tmp folder. The error in that case is the same (no such file or directory). Even though I've just created the folder with the above commands.

答案1

得分: 5

你离答案很近了。你使用exec.Command()的方式还不完全正确。尝试以下代码:

package main

import (
	"fmt"
	"os"
	"os/exec"
)

func main() {
	o, err := exec.Command("ls", "-la", "/tmp").Output()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("%s\n", o)
}

Command()的第一个参数是你想要运行的程序,后面的参数是程序的参数。

参考链接:https://play.golang.org/p/WaVOU0IESmZ

英文:

You are close. The way you use exec.Command() is not yet 100% correct. Try the following:

package main

import (
	"fmt"
	"os"
	"os/exec"
)

func main() {
	o, err := exec.Command("ls", "-la", "/tmp").Output()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("%s\n", o)
}

The first argument to Command() is the program you want to run and all the following arguments are the programs arguments.

See https://play.golang.org/p/WaVOU0IESmZ

huangapple
  • 本文由 发表于 2021年7月7日 21:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/68286918.html
匿名

发表评论

匿名网友

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

确定