James Doe
James Doe

Reputation: 13

Dynamic Threading

Hello I am having an issue with Python Threads.

What I am aiming to do is create a function that launches other functions as a thread when called. Unfortunately I am running into two issues (Besides my lack of knowledge in Python.)

1: If I put quotes around: "globals()[T_Name[i]]()" it treats it as a string and executes the code normally. 2: If I omit the quotes around globals()[T_Name[i]]() it launches the first function immediately and does not process through the rest of the script to launch it as a thread.

If anyone could provide some insight I apologize for the formatting I will be bumping it up to PEP 8 standards eventually.

Code:

import threading
import time

T_Name=("Write_Done", "Write_Pin")
T_Time=[]
Tr=[]
for i, Nu in enumerate(T_Name):
    Tr.append("T" + str(i))
    T_Time.append("0")

def Write_Done():
    while True:
       print("Done")
       time.sleep(5)

def Write_Pin():
    while True:
       print("Pin")
       time.sleep(15)

def Thread_Checker():
    while True:
       time.sleep(5)
       for i, TH in enumerate(T_Time):
           if (time.time() - int(TH)) < 30:
              pass
              #thread is still rocking
           else:
              #thread has failed Time to get her done.
              Tr[i] = threading.Thread(target=("globals()[T_Name[i]]()"))
              print("starting" + T_Name[i])
              Tr[i].daemon = True
              Tr[i].start()
       print("Test if alive")
       if Tr[0].is_alive():
          print("I LIVE!")
       else:
          print("I ded")

Thread_Checker()

Upvotes: 1

Views: 1102

Answers (1)

Graham Dumpleton
Graham Dumpleton

Reputation: 58523

Use a lambda function to create something that is actually callable as the target, but defers the call of what you want until the target is called.

Tr[i] = threading.Thread(target=lambda: globals()[T_Name[i]]())

Upvotes: 1

Related Questions