How can I create a ramdisk in Python?

喜夏-厌秋 提交于 2019-11-28 07:12:22
Epeli

How about PyFilesystem?

http://docs.pyfilesystem.org/en/latest/memoryfs.html#module-fs.memoryfs

http://docs.pyfilesystem.org/en/latest/tempfs.html#module-fs.tempfs

The downside is that you have to access the filesystem with PyFilesystem API, but you can also access the real fs with PyFilesystem.

Because file and directory-handling is so low-level and OS dependent, I doubt anything like what you want exists (or is even possible). Your best bet might be to implement a "virtual" file-system-like set of functions, classes, and methods that keep track of the files and directory-hierarchy created and their content.

Callables in such an emulation would need to have the same signature and return the same value(s) as their counterparts in the various Python standard built-ins and modules your application uses.

I suspect this might not be as much work as it sounds -- emulating the standard Python file-system interface -- depending on how much of it you're actually using since you wouldn't necessarily have to imitate all of it. Also, if written in Pure Python™, it would also be portable and easy to maintain and enhance.

One option might be to inject (monkey patch) modified versions of the methods used in the os module as well as the builtins open and file that write to StringIO files instead of to disk. Obviously this substitution should only occur for the module being tested;

Please read this:

http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile

"Return a file-like object that can be used as a temporary storage area. The file is created using mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected)."

It's all handled for you. Do nothing and it already works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!