Python Forum

Full Version: Threading and Queue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working on a backup script for home use and at the same time learn threading. I was researching about threads and sharing data across threads. All my research lead to queues, and I found examples from the Python documentation and Google. Here is the best I can come up with.

Purpose:
Read data in from a text file in a separate thread and return it to the main thread for displaying.

Problem:
When printing, it prints the text with brackets. For example, KeePass is the text stored in the file, it prints it like this:

['KeePass']

How can I remove the brackets? I need to work with the values in other methods

import threading
import queue


def construct_list(read_file, backup):
    with open(read_file) as read_obj:
        backup.put(read_obj.readlines())
    backup.task_done()


backup_list = queue.Queue()
read_thread = threading.Thread(target=construct_list, args=("list.txt", backup_list,))


read_thread.start()
read_thread.join()

while backup_list.empty() is False:
    print(backup_list.get())
If it is a list, it will print enclosed in brackets, to indicate to the viewer that is is indeed a list.
If you want to print the elements in a list, do:
mylist = ['apples', 'pears', 'oranges']
for item in mylist:
    print(item)
# to print individual items (remembering that the index is zero based)
[python]print(mylist[1])
will print pears.

[/python]
(Oct-16-2017, 04:31 AM)Larz60+ Wrote: [ -> ]If it is a list, it will print enclosed in brackets, to indicate to the viewer that is is indeed a list.
If you want to print the elements in a list, do:
mylist = ['apples', 'pears', 'oranges']
for item in mylist:
    print(item)
# to print individual items (remembering that the index is zero based)
[python]print(mylist[1])
will print pears.

[/python]

Problem is, it's a Queue. Can't use a for loop
You can convert to list:
import queue

q = queue.Queue()

for x in range(4):
    q.put(x)

z = list(q.queue)
print(z)
(Oct-16-2017, 03:52 PM)Larz60+ Wrote: [ -> ]You can convert to list:
import queue

q = queue.Queue()

for x in range(4):
    q.put(x)

z = list(q.queue)
print(z)

Thanks for the feedback. How did you learn multi threading? I posted this same code on SO to ask if I was using Queue properly, and the result was less than pleasing. What resources did you use to learn multi threading? I prefer textbooks, because I attempted to Google, but from the pages I found and the code I produced, it was bad advice.
Actually, I don't use it much, (although I have in several applications),
and I can't really tell you where I learned it. Whenever I need to learn
something new, I'm all over the web looking for bits and pieces until I
have a grasp on the subject.

A good bet it that I learned it right here in the forum!