How to create a virtual file as a memory buffer

Viewed 579

I wrote a tool in python that encrypts/decrypts files, but I want to open those files in nano without needing to create a plain text file. Is it possible to create a virtual file or similar that nano can interface with? The files can be hold in memory at once.

1 Answers

In Linux, there are anonymous, in-memory files that behave like regular ones and can be created using os.memfd_create() (Python 3.8 and higher).

>>> fd = os.memfd_create('test_file')
>>> os.write(fd, b'This is a test file\n')
nano /proc/[pid]/fd/[fd]
It automatically disappears if closed.
>>> os.lseek(fd, 0, os.SEEK_SET)
>>> os.read(fd, 0x100)
b'This is a test file\nIt automatically disappears if closed.\n'
>>> os.close(fd)

More information here:

Related