How do I access data from a python thread

2024/11/14 23:29:32

I have a very simple threading example using Python 3.4.2. In this example I am creating a five threads that just returns the character string "Result" and appends it to an array titled thread. In another for loop iterated five times the threads are joined to the term x. I am trying to print the result x, which should yield a list that looks like ['Resut','Result','Result','Result','Result'] but instead the print command only yields the title of the thread and the fact that it is closed. Im obviously misunderstanding how to use threads in python. If someone could provide an example of how to adequately complete this test case I would be very grateful.

 import threadingdef Thread_Test():return ("Result")number  = 5threads = []for i in range(number):Result = threading.Thread(target=Thread_Test)threads.append(Result)Result.start()for x in threads:x.join()print (x)
Answer

There is a difference between creating a thread and trying to get values out of a thread. Generally speaking, you should never try to use return in a thread to provide a value back to its caller. That is not how threads work. When you create a thread object, you have to figure out a different way of get any values calculated in the thread to some other part of your program. The following is a simple example showing how values might be returned using a list.

#! /usr/bin/env python3
import threadingdef main():# Define a few variables including storage for threads and values.threads_to_create = 5threads = []results = []# Create, start, and store all of the thread objects.for number in range(threads_to_create):thread = threading.Thread(target=lambda: results.append(number))thread.start()threads.append(thread)# Ensure all threads are done and show the results.for thread in threads:thread.join()print(results)if __name__ == '__main__':main()

If you absolutely insist that you must have the ability to return values from the target of a thread, it is possible to override some methods in threading.Thread using a child class to get the desired behavior. The following shows more advanced usage and demonstrates how multiple methods require a change in case someone desires to inherit from and override the run method of the new class. This code is provided for completeness and probably should not be used.

#! /usr/bin/env python3
import sys as _sys
import threadingdef main():# Define a few variables including storage for threads.threads_to_create = 5threads = []# Create, start, and store all of the thread objects.for number in range(threads_to_create):thread = ThreadWithReturn(target=lambda: number)thread.start()threads.append(thread)# Ensure all threads are done and show the results.print([thread.returned for thread in threads])class ThreadWithReturn(threading.Thread):def __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None):super().__init__(group, target, name, args, kwargs, daemon=daemon)self.__value = Nonedef run(self):try:if self._target:return self._target(*self._args, **self._kwargs)finally:del self._target, self._args, self._kwargsdef _bootstrap_inner(self):try:self._set_ident()self._set_tstate_lock()self._started.set()with threading._active_limbo_lock:threading._active[self._ident] = selfdel threading._limbo[self]if threading._trace_hook:_sys.settrace(threading._trace_hook)if threading._profile_hook:threading. _sys.setprofile(threading._profile_hook)try:self.__value = True, self.run()except SystemExit:passexcept:exc_type, exc_value, exc_tb = self._exc_info()self.__value = False, exc_valueif _sys and _sys.stderr is not None:print("Exception in thread %s:\n%s" %(self.name, threading._format_exc()), file=_sys.stderr)elif self._stderr is not None:try:print(("Exception in thread " + self.name +" (most likely raised during interpreter shutdown):"), file=self._stderr)print(("Traceback (most recent call last):"), file=self._stderr)while exc_tb:print(('  File "%s", line %s, in %s' %(exc_tb.tb_frame.f_code.co_filename,exc_tb.tb_lineno,exc_tb.tb_frame.f_code.co_name)), file=self._stderr)exc_tb = exc_tb.tb_nextprint(("%s: %s" % (exc_type, exc_value)), file=self._stderr)finally:del exc_type, exc_value, exc_tbfinally:passfinally:with threading._active_limbo_lock:try:del threading._active[threading.get_ident()]except:pass@propertydef returned(self):if self.__value is None:self.join()if self.__value is not None:valid, value = self.__valueif valid:return valueraise valueif __name__ == '__main__':main()
https://en.xdnf.cn/q/72019.html

Related Q&A

How to tell if a full-screen application is running?

Is it possible in python to tell if a full screen application on linux is running? I have a feeling it might be possible using Xlib but I havent found a way.EDIT: By full screen I mean the WHOLE scree…

Pretty printers for maps throwing a type error

Ive configured pretty printers using http://wiki.eclipse.org/CDT/User/FAQ#How_can_I_inspect_the_contents_of_STL_containers.3F. It successfully works for vector and other containers. However I cant get …

Return PDF generated with FPDF in Flask

I can generate a PDF with an image using the code below. How can I return the generated PDF from a Flask route?from fpdf import FPDF pdf = FPDF() img = input(enter file name) g = img + .jpg pdf.add_p…

Tensorflow not found on pip install inside Docker Container using Mac M1

Im trying to run some projects using the new Mac M1. Those projects already work on Intel processor and are used by other developers that use Intel. I am not able to build this simple Dockerfile: FROM …

Fast fuse of close points in a numpy-2d (vectorized)

I have a question similar to the question asked here: simple way of fusing a few close points. I want to replace points that are located close to each other with the average of their coordinates. The c…

I use to_gbq on pandas for updating Google BigQuery and get GenericGBQException

While trying to use to_gbq for updating Google BigQuery table, I get a response of:GenericGBQException: Reason: 400 Error while reading data, error message: JSON table encountered too many errors, givi…

Something wrong with Keras code Q-learning OpenAI gym FrozenLake

Maybe my question will seem stupid.Im studying the Q-learning algorithm. In order to better understand it, Im trying to remake the Tenzorflow code of this FrozenLake example into the Keras code.My code…

How to generate month names as list in Python? [duplicate]

This question already has answers here:Get month name from number(18 answers)Closed 2 years ago.I have tried using this but the output is not as desired m = [] import calendar for i in range(1, 13):m.a…

Getting ERROR: Double requirement given: setuptools error in zappa

I tried to deploy my Flask app with zappa==0.52.0, but I get an error as below;ERROR: Double requirement given: setuptools (already in setuptools==52.0.0.post20210125, name=setuptools) WARNING: You are…

PySpark - Create DataFrame from Numpy Matrix

I have a numpy matrix:arr = np.array([[2,3], [2,8], [2,3],[4,5]])I need to create a PySpark Dataframe from arr. I can not manually input the values because the length/values of arr will be changing dyn…