How to mount a memory filesystem onto a directory

2.4k Views Asked by At

I have a memory filesystem in Python, created in the following fashion:

import fs
mem_fs = fs.open_fs('mem://')
mem_fs.makedirs('/dir1')
with mem_fs.open('/dir1/file1', 'w') as file1:
    file1.write('test')

I want to mount this filesystem onto a directory in my OS filesystem (e.g., /home/user/mem_dir). I can create an object that would reference OS filesystem:

os_fs = fs.open_fs('/home/user/mem_dir')

But then I have no idea how to go about mounting mem_fs onto os_fs. I tried using MountFS class, but it only creates a virtual filesystem. I need to create a mount point in a way that other external applications (e.g., nautilus) would be able to see it and copy files to/from there. Any feedback would be appreciated.

1

There are 1 best solutions below

2
On BEST ANSWER

I had the same requirement, ans i've managed it this way

from fs.tempfs import TempFS
tmp = TempFS(identifier='_toto', temp_dir='tmp/ramdisk/')

it does mount create a directory, with an arbitrary name suffixed by _toto

tmp/ramdisk ❯❯❯ ls
tmpa1_4azgi_toto

which is totaly available as a standard filesystem in the host as in your python code

tmp/ramdisk/tmpa1_4azgi_toto ❯❯❯ mkdir test                                                                    
tmp/ramdisk/tmpa1_4azgi_toto ❯❯❯ ls                                                                            
test

 >>> tmp.listdir('/')
['test']

it look quite magic as it does not appear at all in the mounted host's filesystem

 ❯❯❯ df -ah | grep -E '(ramdisk|tmp)'                                              
tmpfs                       785M    1,7M  783M   1% /run
tmpfs                       3,9G    195M  3,7G   5% /dev/shm
tmpfs                       5,0M    4,0K  5,0M   1% /run/lock
tmpfs                       3,9G       0  3,9G   0% /sys/fs/cgroup
tmpfs                       785M     36K  785M   1% /run/user/1000

and it does totally disepear when your code end, or when you call

>>> tmp.close()

tmp/ramdisk ❯❯❯ ls
tmp/ramdisk ❯❯❯

Cheers