使用python写入AWS Lambda中的/tmp目录
目标
我正在尝试将zip文件写入python aws lambda的/tmp文件夹中,因此我可以在压缩之前提取操作,并将其放入s3存储桶中.
I'm trying to write a zip file to the /tmp folder in a python aws lambda, so I can extract manipulate before zipping, and placing it in s3 bucket.
问题
Os Errno30只读文件系统
Os Errno30 Read Only FileSystem
此代码在我的计算机上进行了本地测试,以确保在将文件上传到aws之前将文件写入到我的工作目录中.这是我要使用的代码.
This code was tested locally on my computer to make sure the file would write to my working directory before I uploaded it to aws. This is the code i'm trying to use.
file = downloadFile() #This is api call that returns binary zip object
newFile = open('/tmp/myZip.zip','wb')
newFile.write(file)
extractAll('/tmp/myZip.zip')
这是试图提取zip文件的代码
here is the code that is trying to extract the zip file
def extractAll(self,source):
with zipfile.ZipFile(source, 'r') as archive:
archive.extractall()
这是痕迹
[Errno 30] Read-only file system: '/var/task/test-deploy': OSError
Traceback (most recent call last):
File "/var/task/web.py", line 31, in web
performAction(bb, eventBody)
File "/var/task/src/api/web.py", line 42, in performAction
zipHelper.extractAll('/tmp/myZip.zip')
File "/var/task/src/shared/utils/zipfilehelper.py", line 24, in extractAll
archive.extractall()
File "/var/lang/lib/python3.6/zipfile.py", line 1491, in extractall
self.extract(zipinfo, path, pwd)
File "/var/lang/lib/python3.6/zipfile.py", line 1479, in extract
return self._extract_member(member, path, pwd)
File "/var/lang/lib/python3.6/zipfile.py", line 1538, in _extract_member
os.mkdir(targetpath)
OSError: [Errno 30] Read-only file system: '/var/task/test-deploy'
您需要使用 os.chdir()
来更改当前目录:
You need to use os.chdir()
to change the current directory:
import os, zipfile
os.chdir('/tmp')
with zipfile.ZipFile(source, 'r') as archive:
archive.extractall()
更好的是,您可以创建临时目录,然后将文件解压缩到该文件中,以避免污染/tmp
:
Even better, you can create a temporary directory and extract the files there, to avoid polluting /tmp
:
import os, tempfile, zipfile
with tempfile.TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
with zipfile.ZipFile(source, 'r') as archive:
archive.extractall()
如果要在提取文件后还原当前工作目录,请考虑使用此装饰器:
If you want to restore the current working directory after extracting the file, consider using this decorator:
import os, tempfile, zipfile, contextlib
@contextlib.context_manager
def temporary_work_dir():
old_work_dir = os.getcwd()
with tempfile.TemporaryDirectory() as tmp_dir:
os.chdir(tmp_dir)
try:
yield
finally:
os.chdir(old_work_dir)
with temporary_work_dir():
with zipfile.ZipFile(source, 'r') as archive:
archive.extractall()