0

I need to create a virtual file in memory to trick the system and to let it think that it exists.

I have some scientific program and I heed to provide in some function file for output as argument.

I want to create some file in memory and provide this file to this function.

I do not want to use some temp folders and so on. How do you think, is it possible to create this trick?

martineau
  • 119,623
  • 25
  • 170
  • 301
Beliaev Maksim
  • 968
  • 12
  • 21

1 Answers1

2

The io library can create in-memory file like objects that act like file handles opened with the typical f = open(filename, mode). If you would have opened in normal text mode, a StringIO should do the trick, or if you would have opened the file in binary mode, BytesIO is the way to go.

Aaron
  • 10,133
  • 1
  • 24
  • 40
  • 1
    Also [tempfile](https://docs.python.org/3.6/library/tempfile.html) library provides (as it's name suggests) a temporary file-like object. – Gábor Fekete Mar 02 '18 at 16:45
  • unfortunately that does not help. I already tried this before opening a question. It returns empty string. Also for test I tried output.write('test') and getvalue() returned me a result. But when I provide output as an argument to this function outpus is still empty. – Beliaev Maksim Mar 03 '18 at 14:33
  • @BeliaevMaksim what is this function you need to provide a file for? Given the description in your comment, you must have a problem elsewhere then. – Aaron Mar 03 '18 at 18:35
  • @Aaron, I need to provide a file with path as argument. – Beliaev Maksim Mar 06 '18 at 08:31
  • @BeliaevMaksim then the function itself is taking care of opening the file and writing to it. You either need to edit the function itself, or [mount a section of system ram](https://en.wikipedia.org/wiki/RAM_drive) as a logical volume to create the file on. – Aaron Mar 06 '18 at 14:31
  • @Aaron, I think smth like second idea. Is there any chance to make it simple ? – Beliaev Maksim Mar 07 '18 at 14:50
  • @BeliaevMaksim ramdisks are not super standardized across operating systems. Ultimately it's usually managed by an external program rather than being a feature built into the OS. [Wikipedia](https://en.wikipedia.org/wiki/List_of_RAM_drive_software) has a list of existing ramdisk software packages sorted by OS. – Aaron Mar 07 '18 at 22:16