Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Returning data from a threaded def

I have a bit of code that gets the title of a .MP3 file

def getTitle(fileName):
    print "getTitle"
    audio = MP3(fileName)

    try:
        sTitle = str(audio["TIT2"])
    except KeyError:
        sTitle = os.path.basename(fileName)

    sTitle = replace_all(sTitle) #remove special chars

    return sTitle

I would call this function with

sTitle = getTitle("SomeSong.mp3")

To solve another problem I wanted to spawn this on its own thread so I altered my call to

threadTitle = Thread(target=getTitle("SomeSong.mp3"))
threadTitle.start()

This correctly calls the function and solves my other problem, but now I can't figure out how to get the return value of sTitle from the function into Main.

like image 249
ccwhite1 Avatar asked Mar 16 '11 11:03

ccwhite1


People also ask

How do you retrieve data from a thread in Python?

For example: def foo(bar, result, index): print 'hello {0}'. format(bar) result[index] = "foo" from threading import Thread threads = [None] * 10 results = [None] * 10 for i in range(len(threads)): threads[i] = Thread(target=foo, args=('world! ', results, i)) threads[i].

How do you return a value from a thread?

How to Return Values From a Thread. A thread cannot return values directly. The start() method on a thread calls the run() method of the thread that executes our code in a new thread of execution. The run() method in turn may call a target function, if configured.

How do you call a thread in Python?

Use the Python threading module to create a multi-threaded application. Use the Thread(function, args) to create a new thread. Call the start() method of the Thread class to start the thread. Call the join() method of the Thread class to wait for the thread to complete in the main thread.

What is Threadin Python?

Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes.


2 Answers

I would make a new object that extends thread so that you can get anything you want out of it at any time.

from threading import Thread

class GetTitleThread(Thread):        

    def __init__(self, fileName):
        self.sTitle = None
        self.fileName = fileName
        super(GetTitleThread, self).__init__()

    def run(self):
        print "getTitle"
        audio = MP3(self.fileName)

        try:
            self.sTitle = str(audio["TIT2"])
        except KeyError:
            self.sTitle = os.path.basename(self.fileName)

        self.sTitle = replace_all(self.sTitle) #remove special chars


if __name__ == '__main__':
    t = GetTitleThread('SomeSong.mp3')
    t.start()
    t.join()
    print t.sTitle
like image 129
Iacks Avatar answered Sep 19 '22 08:09

Iacks


One way to do it is to use a wrapper storing the result:

def wrapper(func, args, res):
    res.append(func(*args))

res = []
t = threading.Thread(
    target=wrapper, args=(getTitle, ("SomeSong.mp3",), res))
t.start()
t.join()
print res[0]
like image 25
Sven Marnach Avatar answered Sep 21 '22 08:09

Sven Marnach