ricardo.santos
Posts: 43
Joined: Thu Jan 18, 2018 12:18 pm

how to name a class Thread

Sat Mar 10, 2018 11:03 pm

hi

i have a class using a thread as object i think
how can i give it a name. it will help the debugging in pycharm

temp.py

Code: Select all

class WTemp(threading.Thread):
 
    def __init__(self, sleep):
        threading.Thread.__init__(self)
        self.sleep = sleep
        self.W_temp = 0
 
    def run(self):
        while True:
            # reads every sleep interval >0.8 (sensor response minimum delay)
            self.W_temp = W1ThermSensor().get_temperature()
            time.sleep(self.sleep)
 
    def read_temp(self):
        water_temp = self.W_temp
main.py

Code: Select all

from temp import Wtemp
 
Wtemp.start()
how do i give a name to the thread .
in pycharm it appears as Thread7

thanks

User avatar
Paeryn
Posts: 2712
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: how to name a class Thread

Sun Mar 11, 2018 4:26 am

To name a threading object you just set its name property (or pass it a name when you initialise it). I assume pycharm uses that property as I have no knowledge of how pycharm works.

Your example main.py won't work as you gave it, wrong capitalisation of WTemp and you try calling the class function start() directly instead of creating an object of WTemp and calling its start() method.

Code: Select all

# temperature_sensor.py

import threading

class WTemp(threading.Thread):
  def __init__(self, sleep):
    threading.Thread.__init__(self, name = 'Default WTemp thread name')
    self.sleep = sleep
    self.W_temp = 0

Code: Select all

# main.py

from temperature_sensor import WTemp

temperature_sensing_thread = WTemp(1)
temperature_sensing_thread.name = 'My temperature thread'
temperature_sensing_thread.start()
She who travels light — forgot something.

ricardo.santos
Posts: 43
Joined: Thu Jan 18, 2018 12:18 pm

Re: how to name a class Thread

Sun Mar 11, 2018 9:14 am

:idea:
so simple. thanks a lot . that works like a charm in pycharm

why the 1 inside brackets? is that needed

User avatar
Paeryn
Posts: 2712
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: how to name a class Thread

Sun Mar 11, 2018 12:17 pm

ricardo.santos wrote:
Sun Mar 11, 2018 9:14 am
:idea:
so simple. thanks a lot . that works like a charm in pycharm

why the 1 inside brackets? is that needed
Your class constructor as you gave it requires a value for sleep, it won't work if you don't pass it a number :-

Code: Select all

class WTemp(threading.Thread):
  def __init__(self, sleep):
She who travels light — forgot something.

Return to “Python”