帮助函数识别和使用可以创建基于RAM的TestFrm的OS(仅用于现在的Linux)上的路径。
memory-tempfile的Python项目详细描述
概述
通常需要临时将文件保存到“磁盘”以使用外部工具。或者您可以将一些输入信息管道到外部工具 但无法强制这种外部工具将其输出直接管道到您的软件:它希望将文件写入磁盘。 磁盘操作很慢,如果重复得太频繁,可能会缩短底层介质的寿命。
在Linux上,大多数发行版都提供/tmp目录,但它位于物理介质上。然而,现代发行版通常在东二线发行 在ram中可以安全地创建临时文件的位置:dev/run/<;uid>;、/run/shm和/dev/shm
/dev/run/<;uid>;是临时文件的理想选择。它只能由您的用户写入和读取。 /dev/shm通常是全局可读和全局可写的(就像/tmp一样),它通常用于ipc(进程间通信),但也可以用作临时的基于ram的tempdir
这个模块非常简单,并试图不重新发明轮子。它将检查/tmp,看看它是否在ramdisk中。它也会检查 如果您有其他选项,可以将临时文件/目录放在基于内存的文件系统(如tmpfs或ramfs)上。
有了这些信息,pythons内置模块和外部包(如pathlib或pyfilesystem2)就可以很好地为您服务,让您继续执行您的任务。
要了解更多信息,我建议使用以下链接:https://unix.stackexchange.com/questions/162900/what-is-this-folder-run-user-1000https://superuser.com/questions/45342/when-should-i-use-dev-shm-and-when-should-i-use-tmp
API
此模块搜索驻留在属于基于mem的文件系统(“tmpfs”或“ramfs”)类型的文件系统上的路径。 搜索SUBITABLE路径中的路径,找到存在的第一路径,并将其存储在其类型的文件系统中。 属于mem_-based_fs将用作tempdir。 如果没有找到合适的路径,那么如果fallback=true,我们将回滚到默认的tempdir(由tempfile stdlib决定)。如果回退是一条路径,那么我们将默认它。 如果fallback为false,则会引发运行时错误异常。
memorytempfile构造函数有参数,可以让您更改算法的工作方式。 您可以更改路径的顺序(使用首选路径),向seach添加新路径(使用首选路径和/或其他路径) 并且可以排除某些路径(带有已删除的路径)。 您可以更改接受的文件系统类型(使用文件系统类型),并指定是否作为最后手段回退到普通tempdir。
然后,tempfile stdlib提供的所有方法都可以通过memorytempfile获得。
用法
示例1:
from memory_tempfile import MemoryTempfile
tempfile = MemoryTempfile()
with tempfile.TemporaryFile() as
# as usual...
例2:
# We now do not want to use /dev/shm or /run/shm and no ramfs paths
# If /run/user/{uid} is available, we prefer it to /tmp
# And we want to try /var/run as a last resort
# If all fails, fallback to platform's tmp dir
from memory_tempfile import MemoryTempfile
import memory_tempfile
# By the way, all paths with string {uid} will have it replaced with the user id
tempfile = MemoryTempfile(preferred_paths=['/run/user/{uid}'], remove_paths=['/dev/shm', '/run/shm'],
additional_paths=['/var/run'], filesystem_types=['tmpfs'], fallback=True)
if tempfile.found_mem_tempdir():
print('We could use any of the followig paths: {}'.format(tempfile.get_usable_mem_tempdir_paths()))
print('And we are using now: {}'.format(tempfile.gettempdir()))
with tempfile.NamedTemporaryFile() as ntf:
# use it as usual...
pass