SoFunction
Updated on 2024-11-19

Sample python implementation of progress bars and system notifications in detail

Took a break to work on two of the more interesting scripts that work well in everyday use.

Today's code display differs from the previous code image display by showing the code directly.shigenRevised the engine and some of the styles of the md to microsoft typography overnight.

Download web files and show progress

import click
from tqdm import tqdm
import requests

@()
@("-url", "--url", help="file url", required=True)
@("-name", "--name", help="Picture rename")
def file(url, name):
    """File download"""
    _download(url, name)

def _download(url, name):
    if not name:
        name = get_file_name(url)
    resp = (url, stream=True)

    # Get file size
    file_size = int(['content-length'])

    with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024, ascii=True, desc=name) as bar:
        with (url, stream=True) as r:
            with open(name, 'wb') as fp:
                for chunk in r.iter_content(chunk_size=512):
                    if chunk:
                        (chunk)
                        (len(chunk))

# Parse the file name
def get_file_name(url):
    if '?' in url:
        return ('?')[0].split('/')[-1]
    else:
        return ('/')[-1]
    
    
if __name__ == '__main__':
    file()

The following packages need to be installed before use:

pip install click tqdm

Among them.clickis a very interesting tool for parsing command line arguments, much more so than theargsparseIt works better;tqdmis commonly used for progress bar display.

What are the effects like? We'll see together:

System notification

Let's look at the code first:

from plyer import notification
import psutil
from time import sleep
while True:
    battery = psutil.sensors_battery()
    life = 
    if life < 60:
        (
            title = "Battery Low",
            message = "Please connect to power source",
            timeout = 10
        )
    sleep(60)

The effect of the implementation is that the notification is executed every 1 minute, and the condition of the notification is the currentlifeThat is, the notification box appears when the battery level is less than 60:

Libraries that need to be installed in advance are:

pip install plyer

Attention:

This script is only executed in windows system to test the effect, macos system is still to be verified, interested partners can try. latershigenWill also share efficiency scripts based on the magic of this script.

to this article on the implementation of python progress bar and system notification of the sample details of the article is introduced to this, more related python progress content please search my previous posts or continue to browse the following related articles I hope that you will support me more in the future!