Home > database >  Is there a way to view a piece of data from a python script as a Linux file?
Is there a way to view a piece of data from a python script as a Linux file?

Time:08-06

For example, since Linux uses the “everything is a file” philosophy, I can get the cpu temp by running cat /sys/class/thermal/thermal_zone*/temp

Is there a way to create a file tree that shows python variables in the same way?

If I had a script checking the temperature outside, could I output the data as “/somefolder/temperature/outside”?

Then if I ran cat /somefolder/temperature/outside it would return “50°”

I figure I could constantly update a text file, but since I’m using an ssd I am hesitant to constantly be rewriting an actual on disk file. Especially when I don’t need the data to persist.

CodePudding user response:

I've gone down the rabbit hole for you here. Heres what ive found:

  1. There is a concept called memory mapping a file. As in taking a file and mapping that to a piece of memory that your process can change. This is fine but we want the other way round. You want to have a piece of memory mapped to disk.
  2. Where a file lives (memory or disk) is not an attribute of the file. Its an attribute of the filesystem the file is written to. As in, If my filesystem lives on disk then the files created on that filesystem is created on disk. If my filesystem lives in memory then the files will as well.
  3. Not all storage drivers can memory map files. From what ive seem the most common one is just tmpfs.

if you run df -h on a linux machine you will see something close to:

Filesystem      Size  Used Avail Use% Mounted on
...
tmpfs           796M  1.5M  794M   1% /dev/shm
...

Now, anything with Filesystem as tmpfs is a filesystem that is in memory and not on disk.

So lets see if we can make a file and what it does. Will it increase memory or storage?

dd if=/dev/zero of=/dev/shm/test.dat  bs=500M  count=1

This just creates a file of a specific size and we can see whats happening. running that we see a jump in memory usage: enter image description here

and removing it:

rm /dev/shm/test.dat

enter image description here

Cool. Seems like the file im making is indeed stored in memory. Now how do we do this in python? Since i believe /dev/shm is standard on linux we can just make a file in there:

import time

f = open('/dev/shm/myvalue', 'w')
i = 0

while i < 100000:
    f.truncate(0)
    f.write("My custom Value: "   str(i))
    f.flush()
    i = i   1
    time.sleep(1)

and cat it as it goes along:

$> cat /dev/shm/myvalue
My custom Value: 5
$>
  • Related