-1

I have a list containing [bool, "string of function name", ["parameters","to","pass"]] but when I pass them, they don't resolve to anything but their string values. The actual project is around 900+400 lines already so for brevity and sanity I have included the important bits below:

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath('.'), relative_path)

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi(resource_path('./hc-gui.ui'), self)
        # a bunch of QPushButton connected functions from a loaded .ui file made in QT Designer
        global dxt
        dxt = pydxt.laid(pydxt.fetch()) 
        # pydxt is a module I wrote specifically for this workplace and project 
        # laid() returns [[name, ip, user, pass, 6-digit id, laidrange_start, laidrange_end, associated_letter]] as end result, and is used below
        # the dxt list serves as basis for all such basic information
        
    def runButton(self):
        global runlist
        runlist = []
        for i in range(self.listLaid.count()):
            item = self.listLaid.item(i)
            runlist.append(str(item.text()))
            # there is now a list of each LAID to process
        global checklist
        checklist = []
        togglebuttons = [
            [self.toggleTTRX, "checkTTRX", ["host","usr","passwd","tbs"]],
            [self.toggleMCCH, "checkMCCH", ["host","usr","passwd","laid"]],
            [self.toggleRL, "checkRL", ["host","usr","passwd","tbs","sitedown"]],
            [self.toggleGPS, "checkGPS", ["host","usr","passwd","tbs","sitedown"]]
            ]
        for i in range(len(togglebuttons)):
            checklist.append([togglebuttons[i][0].isChecked(), togglebuttons[i][1], togglebuttons[i][2]])
        self.runLongTask()
        
    def runLongTask(self):
        self.worker = Worker()
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.finished.connect(self.presentResults)
        self.thread.finished.connect(self.thread.deleteLater)
        QApplication.processEvents()
        self.thread.started.connect(lambda: self.worker.connectAndParse(runlist, checklist))
        self.thread.start()
        
class Worker(QObject):
    finished = pyqtSignal()
    logit = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        
    def connectAndParse(self, runlist, checklist):
        global results
        results = []
        for x in range(len(runlist)):
            laid = str(runlist[x])
            hostlist = pydxt.finder(dxt,int(laid)) # just finds correct dxt based on provided laid, returns correct sublist from dxt list
            tbs = str(int(laid)-int(hostlist[5])+1)
            host = hostlist[1]
            usr = hostlist[2]
            passwd = hostlist[3]
            global sitedown
            sitedown = False
            runtask = Worker()
            for y in range(len(checklist)):
                if bool(checklist[y][0]):
                    func = getattr(runtask, checklist[y][1])(*checklist[y][2]
                    results.append(func())
        self.finished.emit()

    def checkTTRX(self, host, usr, passwd, tbs):
        with telnetlib.Telnet(host=host,timeout=2) as tn:
            tn.write(usr.encode('ascii' + b"\r\n")
            tn.write(passwd.encode('ascii' + b"\r\n")
            #etc etc
            number = ""
            return ["number of ttrx on site", number]
    
    def checkMCCH(self, host, usr, passwd, laid):
        with telnetlib.Telnet(host=host,timeout=2) as tn:
            #does more stuff, checks if sitedown should remain as False or be set to True
            
    def checkRL(self, host, usr, passwd, tbs, sitedown):
        #same story here, just keeps going

I am sure I have missed something blatantly obivous, as I am still learning how to work with multiple classes. Previously all the stuff that was in the now separated check-functions were in a huuuge block and mandatory to process, I wanted to make everything optional instead.

The error I get is that Telnet cannot resolve the hostname, because host doesn't resolve to an ip address but just a string of "host".

The problem (as I see it) is rooted in my list of parameters that need resolving don't resolve and I don't know how to. How can I pass a list of which parameters to use from Ui class to the Worker class where they can be resolved as the variables with the same names?

Chokehold
  • 67
  • 7
  • You can't refer to local variables in another function, especially not local variables that don't even exist at the time the code is run. The function name issue is solvable (`Worker.checkTTRX` instead of the string `"checkTTRX"`), but not the local variables. You could just pass the same set of parameters to ALL the `check` functions and let them ignore the ones they don't want. Or, put them into a dict and let the checklist filter out only certain elements. – Tim Roberts Aug 23 '21 at 21:53
  • Why use `runtask = Worker()` instead of just `runtask = self`? – Tim Roberts Aug 23 '21 at 21:53
  • @TimRoberts It was a hail Mary really, throwing a bunch of stuff against the wall and seeing what stuck, that was the last attempt but didn't get me anywhere. It wasn't a conscious choice, but rather the last attempt at getting anywhere at all. – Chokehold Aug 23 '21 at 22:00
  • In my PERSONAL opinion, you should establish a standard interface for all of your `check` functions, and have them all use exactly the same signature. Let them ignore the parameters they don't want. That eliminates most of your troubles. – Tim Roberts Aug 23 '21 at 22:05
  • That seems to have gotten me farther. Added the respective parameters to a single `args` list and put `*args` as parameter when using `getattr`. Also on the line below I changed it to `append(func)` instead of `append(func())` since what gets returned from the functions are lists. Feel free to add your personal opinion as an answer and I'll mark it. – Chokehold Aug 23 '21 at 22:32

1 Answers1

1

In my PERSONAL opinion, you should establish a standard interface for all of your check functions, and have them all use exactly the same signature. Let them ignore the parameters they don't want. That eliminates most of your troubles.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30