Bir Nechta Fayllarni Threadlar Bilan Yozish

Python threads.

SU

Bir Nechta Fayllarni Threadlar Bilan Yozish

Threadlardan foydalanishning bir nechta keng tarqalgan holatlari mavjud. Ulardan biri — bir vaqtda bir nechta fayllarni yozish. Haqiqiy dunyo muammosini qanday hal qilishni ko'rish juda qiziqarli, shuning uchun mana shu yerda buni amalga oshirishingizni ko'rib chiqamiz.

Boshlash uchun writing_thread.py nomli fayl yarating. Keyin faylingizga quyidagi kodni qo'shing:

# writing_thread.py
 
import random
import time
from threading import Thread
 
class WritingThread(Thread):
 
    def __init__(self,
                 filename: str,
                 number_of_lines: int,
                 work_time: int = 1) -> None:
        Thread.__init__(self)
        self.filename = filename
        self.number_of_lines = number_of_lines
        self.work_time = work_time
 
    def run(self) -> None:
        """
        Threadni ishga tushirish
        """
        print(f'{self.number_of_lines} qator matnni '
              f'{self.filename} fayliga yozish')
        with open(self.filename, 'w') as f:
            for line in range(self.number_of_lines):
                text = f'This is line {line+1}\n'
                f.write(text)
            time.sleep(self.work_time)
        print(f'{self.filename} fayliga yozish tugadi')
 
if __name__ == '__main__':
    files = [f'test{x}.txt' for x in range(1, 6)]
    for filename in files:
        work_time = random.choice(range(1, 3))
        number_of_lines = random.choice(range(5, 20))
        thread = WritingThread(filename, number_of_lines, work_time)
        thread.start()

Endi kodni tahlil qilaylik:

1-3 qatorlar:
random, time va Thread ni import qilasiz. random orqali tasodifiy sonlar generatsiya qilinadi, time esa vaqt bilan bog'liq funksiyalarni bajaradi, Thread esa threadlarni yaratish uchun kerak bo'ladi.

6-18 qatorlar:
Bu yerda WritingThread klassini yaratdingiz. Bu klass fayl nomi, yoziladigan qatorlar soni va ish vaqti (default qiymati 1 sekund) kabi parametrlarni qabul qiladi. Bu parametrlar yordamida siz ma'lum sonli qatorlardan iborat matn faylini yaratishingiz mumkin. work_time — har bir qatorni yozishdan oldin kutish vaqti.

run() metodini ko'rib chiqamiz:

def run(self) -> None:
    """
    Threadni ishga tushirish
    """
    print(f'{self.number_of_lines} qator matnni '
          f'{self.filename} fayliga yozish')
    with open(self.filename, 'w') as f:
        for line in range(self.number_of_lines):
            text = f'This is line {line+1}\n'
            f.write(text)
        time.sleep(self.work_time)
    print(f'{self.filename} fayliga yozish tugadi')

Bu kodda, siz faylga nechta qator yozishingizni chiqarasiz. Keyin faylni yaratib, matnni qo'shasiz. Faylga yozish jarayonida sleep() yordamida vaqt qo'shib, yozish jarayonini simulyatsiya qilasiz.

Oxirgi kod blokini ko'rib chiqamiz:

if __name__ == '__main__':
    files = [f'test{x}.txt' for x in range(1, 6)]
    for filename in files:
        work_time = random.choice(range(1, 3))
        number_of_lines = random.choice(range(5, 20))
        thread = WritingThread(filename, number_of_lines, work_time)
        thread.start()

Bu kodda, siz 5 ta fayl nomidan iborat ro'yxat yaratish uchun list comprehensiondan foydalanasiz. Keyin fayllarni birma-bir aylanib chiqasiz va har bir fayl uchun tasodifiy ish vaqi va qatorlar sonini tanlaysiz. So'ngra, WritingThread yaratib, start() metodini chaqirasiz.

Kod ishga tushirilganda quyidagi kabi natijani ko'rishingiz mumkin:

Writing 5 lines of text to test1.txt
Writing 18 lines of text to test2.txt
Writing 7 lines of text to test3.txt
Writing 11 lines of text to test4.txt
Writing 11 lines of text to test5.txt
Finished writing test1.txt
Finished writing test3.txt
Finished writing test4.txt
Finished writing test5.txt
Finished writing test2.txt

E'tibor bering, ba'zi xato chiqishlar bo'lishi mumkin, masalan, oxirgi qatorda yozilganlarni bir nechta thread bir vaqtda standart chiqish (stdout) ga yozishgan bo'lishi mumkin.

Ushbu kodni urllib.request bilan birgalikda ishlatib, Internetdan fayllarni yuklab olish uchun ilova yaratishingiz mumkin. O'zingiz sinab ko'ring!

Last updated on

On this page

Xato haqida xabar berish