Thursday, July 28, 2022

How to copy file in python with progress bar

Можно использовать внешнюю библиотеку Python tqdm для создания простых и удобных индикаторов выполнения, которые вы можете добавить в свой код и сделать его живым.Использовать tqdm очень просто, вам просто нужно добавить свой код между tqdm() после импорта библиотеки в ваш код. Вы должны убедиться, что код, который вы вставляете между функцией tqdm(), должен быть итерируемым, иначе он вообще не будет работать.

Iterable — это объект, который можно перебирать или повторять с помощью цикла for. Такие объекты, как списки, кортежи, наборы, словари, строки и т. д., называются итерируемыми. Короче говоря, iterable — это все, что вы можете перебрать в цикле.

(.env) boris@boris-All-Series:~/PROGRESSB$ cat progressBar.py

import os

from io import BytesIO

from tqdm import tqdm

file = '../Downloads/ubuntu-22.04-desktop-amd64.iso'

fsize = int(os.path.getsize(file))

new = './ubuntu-22.04-desktop-amd64.iso'

with open(file, 'rb') as f:

 with open(new, 'ab') as outData:

   with tqdm(ncols=60,total=fsize,bar_format='{l_bar}{bar}|Remaining:{remaining}') as pbar: 

         buffer = bytearray()

         while True:

            buf = f.read(16384)

            outData.write(buf)

            if len(buf) == 0:

                     break

            buffer += buf

            pbar.update(len(buf))

(.env) boris@boris-All-Series:~/PROGRESSB$ ll

total 16

drwxrwxr-x   3 boris boris 4096 июл 28 11:07 ./

drwxr-xr-x 132 boris boris 4096 июл 28 10:49 ../

drwxrwxr-x   6 boris boris 4096 июл 28 10:31 .env/

-rw-rw-r--   1 boris boris  570 июл 28 11:04 progressBar.py

(.env) boris@boris-All-Series:~/PROGRESSB$ cat progressBar.py

import os

from io import BytesIO

from tqdm import tqdm

file = '../Downloads/ubuntu-22.04-desktop-amd64.iso'

fsize = int(os.path.getsize(file))

new = './ubuntu-22.04-desktop-amd64.iso'

with open(file, 'rb') as f:

 with open(new, 'ab') as outData:

   with tqdm(ncols=60,total=fsize,bar_format='{l_bar}{bar}|Remaining:{remaining}') as pbar: 

         buffer = bytearray()

         while True:

            buf = f.read(16384)

            outData.write(buf)

            if len(buf) == 0:

                     break

            buffer += buf

            pbar.update(len(buf))

(.env) boris@boris-All-Series:~/PROGRESSB$ python3 progressBar.py

100%|███████████████████████████████████████|Remaining:00:00

(.env) boris@boris-All-Series:~/PROGRESSB$ ll

total 3569316

drwxrwxr-x   3 boris boris       4096 июл 28 11:07 ./

drwxr-xr-x 132 boris boris       4096 июл 28 10:49 ../

drwxrwxr-x   6 boris boris       4096 июл 28 10:31 .env/

-rw-rw-r--   1 boris boris        570 июл 28 11:04 progressBar.py

-rw-rw-r--   1 boris boris 3654957056 июл 28 11:07 ubuntu-22.04-desktop-amd64.iso






























































No comments:

Post a Comment