[PYTHON] I want to get angry with my mom when my memory is tight

Even in 2020, I am still alive while worrying about memory

On an 8GB laptop, VSCode + some build + 20 tabs open in Chrome ** will run out of memory in a blink of an eye **. It is a very strict user experience such as stall for each OS.

When I think about it, since I was a child, I was often reprimanded by my mother for leaving things out. Rather than just a lack of memory capacity, it may be due to the difficult-to-heal childhood.

I feel that it would be better to get angry with my mother each time than to correct my behavior. So, create a ** mother-like app ** that warns you to close unnecessary software on your desktop when memory is tight.

Environment / Language

--Ubuntu18.04 + gnome3 environment

Get the available memory capacity

To get the amount of memory available on Linux, you generally use the ** free command **.

$ free
              total        used        free      shared  buff/cache   available
Mem:        8124668     4831144      267628      201468     3025896     2774924
Swap:       2097148         512     2096636

Of these, the available real memory capacity is ** the available column in the Mem row **. Roughly speaking, this value is calculated by ** [free space + capacity that can be released immediately such as used cache] **.

The content of this free command is a formatted version of the content of the / proc / meminfo pseudo file. Files are easier to handle to use from python, so pick up information from ** / proc / meminfo **.

~$ cat /proc/meminfo 
MemTotal:        8124668 kB
MemFree:          328384 kB
MemAvailable:    2640012 kB
Buffers:          740992 kB
・ ・ ・(Abbreviation)

Try opening the file on the interactive shell. Use the split () function to separate line breaks and spaces, and check the order in which Available comes.

>>> f = open('/proc/meminfo')
>>> f.read().split()
['MemTotal:', '8124668', 'kB', 'MemFree:', '318860', 'kB', 'MemAvailable:', '2631456', 'kB', ...]
>>> f.seek(0)
0
>>> f.read().split()[7]
'2625528'

** A notification should be given when an element with an index of 7 falls below 0.5GB (500,000kB). ** ** (The basis for 0.5GB is somehow)

By the way, as you can see from the above example, the contents are updated ** every time you read ** even after opening.

Skip notifications to the desktop

Use the notify-send command. The format is as follows.

$ notify-send -u critical --icon=Icon name"title" "message"

--Specify the notification type in -u. I'm angry at the content, so I think it's okay to be critical. --You can specify the icon with --icon. You can also specify a custom icon. See below. --You can use simple markup in your messages.

Make an icon

I borrowed a mother icon from Mr. Irasutoya and used it (I also considered a live-action mother, but it was powerful and I felt the emotional resentment).

shikaruhaha.png

Place the completed icon as ** shikaruhaha.png ** under ** / usr / share / pixmap . (If you place it in a place other than / usr / share / pixmap, you must specify the path). - Omit the extension when specifying with icon. ** **

$ notify-send -u critical --icon=shikaruhaha "Mother's voice" "<b>J( 'д')Takashi! You're not leaving it messy!</b>"

When you execute the above, it becomes like this.

notify.png

code

memwarn.py


#!/usr/bin/python3
import time
import subprocess

with open("/proc/meminfo") as f:
    while(True):
        f.seek(0)
        arr = f.read().split()
        available = int(arr[7])
        if available < 500000:
            subprocess.call(['notify-send', "-u", "critical", "--icon=shikaruhaha", "Mother's voice", "<b>J( 'д')Takashi! You're not leaving it messy!</b>"])
        time.sleep(2)

--Loop every 2 seconds --Forcibly return the read position with f.seek (0) (because once read, the read position will be at the end) --Use ** subprocess.call ** to execute the shell. Pass shell commands in a space-separated list of strings. -Give execute permission with the file name ** memwarn.py ** and place it under ** / usr / libexec / **.

Deploy

Start after logging in in the X environment. Place the following files under / etc / xdg / autostart /. After logging in, it will start automatically.

/etc/xdg/autostart/memwarn.desktop


[Desktop Entry]
Name=MemoryMother
Type=Application
Exec=/usr/libexec/memwarn.py
OnlyShowIn=GNOME;
NoDisplay=true

That's it

Summary

--Don't tell me to add more memory ――No matter how much you are too dependent -** Actually, it's not the name "Takashi" **

reference

Recommended Posts

I want to get angry with my mom when my memory is tight
I want to get started with the Linux kernel, what is the list head structure?
I want to do ○○ with Pandas
I want to debug with Python
A memorandum when I tried to get it automatically with selenium
I get an error when trying to install maec 4.0.1.0 with pip
I want to check the position of my face with OpenCV!
I want to detect objects with OpenCV
I tried to get started with Hy
I want to blog with Jupyter Notebook
I want to pip install with PythonAnywhere
When I get an error with PyInstaller
I want to analyze logs with Python
I want to play with aws with python
When you want to use it as it is when using it with lambda memo
I want to express my feelings with the lyrics of Mr. Children
I get a UnicodeDecodeError when trying to connect to oracle with python sqlalchemy
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
I want to get the path of the directory where the running file is stored.
I want to have recursion come to my mind
I want to use MATLAB feval with python
I want to analyze songs with Spotify API 2
I want to mock datetime.datetime.now () even with pytest!
I want to display multiple images with matplotlib.
I want to knock 100 data sciences with Colaboratory
I want to make a game with Python
I want to be an OREMO with setParam!
I tried to get CloudWatch data with Python
[OpenCV] When you want to check if it is read properly with imread
I want to analyze songs with Spotify API 1
I get a UnicodeDecodeError when running with mod_wsgi
I want to make fits from my head
I want to use Temporary Directory with Python2
5 Reasons Processing is Useful for Those Who Want to Get Started with Python
I want to get League of Legends data ③
[python] [vscode] When you get angry with space-tab-mixed
I want to get League of Legends data ②
I don't want to use -inf with np.log
#Unresolved I want to compile gobject-introspection with Python3
I want to use ip vrf with SONiC
I want to solve APG4b with Python (Chapter 2)
I want to start over with Django's Migrate
I want to get League of Legends data ①
I want to write to a file with Python
I want to be notified when the command operation is completed on linux!
[Python] I want to use only index when looping a list with a for statement
When I try to install mysqlclient with Django, I get error: command'gcc' failed with exit status 1.
What I did when I was angry to put it in with the enable-shared option
I want to get an error message in Japanese with django Password Change Form
When the variable you want to superscript with matplotlib is two or more characters
I want to convert an image to WebP with lollipop
I want to detect unauthorized login to facebook with Jubatus (1)
I want to transition with a button in flask
I want to handle optimization with python and cplex
I want to climb a mountain with reinforcement learning
I tried to get started with blender python script_Part 01
I want to refute "Ruby is not cool here"
Settings when you want to run python-mecab with travis
I tried to get started with blender python script_Part 02
When you want to filter with Django REST framework
I want to inherit to the back with python dataclass