Search code examples
pythonmemorypsutil

Separate a part of a python output then convert it into another unit


I know the title makes it sounds all complicated, but it is actually simple.

So I am trying to collect system data with python, and I am using the psutil module with python 3.6. I want to find used memory, so I did the command psutil.virtual_memory(). However, the output I got was svmem(total=8535257088, available=3911340032, percent=54.2, used=4623917056, free=3911340032).

I only want to keep the used=4623917056 part of the output. How would I seperate that part from the output?

Also, used=4623917056 is in bytes. I want to convert it to gigabytes, and keep the result to the 3 most significant digits (in this case it would be 4.62). How would I do this as well?


Solution

  • Use the simplest one:

    round(psutil.virtual_memory().used /(1024 ** 3),2)
    

    in python round() function will have two arguments one is value itself and other is a number of digits you want to keep after the decimal.