You are probably looking for BytesIO or StringIO classes from Python io package, both available in python 2 and python 3. They provide a file-like interface you can use in your code the exact same way you interact with a real file.
StringIO is used to store textual data:
import io
f = io.StringIO("some initial text data")
BytesIO must be used for binary data:
import io
f = io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01")
To store MP3 file data, you will probably need the BytesIO class. To initialize it from a GET request to a server, proceed like this:
import requests
from pygame import mixer
import io
r = requests.get("http://example.com/somesmallmp3file.mp3")
inmemoryfile = io.BytesIO(r.content)
mixer.music.init()
mixer.music.load(inmemoryfile)
mixer.music.play()
# This will free the memmory from any data
inmemoryfile.close()
Additional note: as both classes inherit from IOBase, they can be used as context manager with the with statement, so you don't need to manually call the close() method anymore:
import requests
from pygame import mixer
import io
r = requests.get("http://example.com/somesmallmp3file.mp3")
with io.BytesIO(r.content) as inmemoryfile:
mixer.music.init()
mixer.music.load(inmemoryfile)
mixer.music.play()
Answer from Antwane on Stack Overflow(C# || Python/Windows) Is there a way I can create an in-memory file that has a path other processes can access?
Include in-memory fs into python path
memfile: Python library to store files in RAM
Writing File to Memory
I feel like this might be a situation where OS features like pipes could come into play but I'm not knowledgable enough about that stuff, and would appreciate any advice or clarification.
I'm writing a program that deals with image data, reading files into arrays of pixels in memory. The library I'm using knows how to decode JPEGs and PNGs, but not some more niche cutting-edge formats like JPEG XL. So currently when I need to deal with those I create a subprocess, call ImageMagick or djxl (JPEG XL -> JPEG decoder program) to create a temporary .JPEG/.PNG file on the disk, read that, then delete it.
Which works fine, but this isn't optimal: the program could leave temp files on the disk if it's killed before cleaning up (e.g. power failure), it could write millions of temp files for large runs creating unnecessary wear and tear on an SSD, it could spin up a sleeping HDD on a laptop causing battery drain, etc. The temp files are never over 3 MB so it'd be nice to create them in memory instead.
But I'm not sure how I'd go about doing that short of creating a ramdisk. The programs I call in the subprocess want file paths to read from and write to.
So is this a situation where you can create a pipe and use the pipe like a file path, and have the C#/Python program read from it? What's the best approach here?
» pip install memory-profiler