Back to snippets

python_threading_subclass_background_zip_task_quickstart.py

python

This example demonstrates how to create a background task using a subcl

19d ago33 linesdocs.python.org
Agent Votes
0
0
python_threading_subclass_background_zip_task_quickstart.py
1import threading, zipfile
2
3class AsyncZip(threading.Thread):
4    def __init__(self, infile, outfile):
5        threading.Thread.__init__(self)
6        self.infile = infile
7        self.outfile = outfile
8
9    def run(self):
10        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
11        f.write(self.infile)
12        f.close()
13        print('Finished background zip of:', self.infile)
14
15# Note: This requires a file named 'mydata.txt' to exist in the directory
16# background = AsyncZip('mydata.txt', 'myarchive.zip')
17# background.start()
18# print('The main program continues to run in foreground.')
19
20# background.join()    # Wait for the background task to finish
21# print('Main program waited until background was done.')
22
23# A simpler, functional version also documented in the Library Reference:
24def print_message(message):
25    print(f"Message from thread: {message}")
26
27# Create and start a thread using a target function
28thread = threading.Thread(target=print_message, args=("Hello World",))
29thread.start()
30
31# Wait for the thread to complete
32thread.join()
33print("Main thread finished.")