How to create a list and append to list inside a mqtt and GUI program?

MRAB python at mrabarnett.plus.com
Sun Sep 1 20:26:55 EDT 2019


On 2019-09-01 21:02, Spencer Du wrote:
> Hi
> 
> I have code for GUI and MQTT. In GUI.py I have "def loadGUI" which loads up a GUI file if the file exists in current directory. I want to add the file name to a list when a file is imported and for each subsequent file that is imported I want the file name to be imported to the same list and print the list or create a new list but with the imported file named added to list which has the existing file names that have already been imported. I was wondering how I do this. By the way run GUI.py to test this and test1.py and test2.py are the files which can be used to import GUI .
> 
> GUI.py
[snip]
import json
> 
[snip]
>      def loadGUI(self):
>          print("Searching file", self.fileName_UI)
>          try:
>              module = __import__(self.fileName_UI)
>              my_class = getattr(module, "SubWindow")
> 
>              sub = QMdiSubWindow()
> 
>              sub.setWidget(my_class())
>              sub.setWindowTitle("New GUI:  " + self.fileName_UI)
>              self.mdi.addSubWindow(sub)
>              sub.show()
> 
>              print("creating new instance " + self.fileName_UI)
>              client = device("Device")
>              client.run()
> 
>              client.loop_start()  # start the loop
>              device_message = self.fileName_UI
>              time.sleep(2)
>              print("Subscribing to topic", "microscope/light_sheet_microscope/UI")
>              client.subscribe("microscope/light_sheet_microscope/UI")
>              print("Publishing message to topic", "microscope/light_sheet_microscope/UI")
>              client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": "device", "payload":{"name": self.fileName_UI, "cmd": "adding device"}}, indent=2))
>              time.sleep(1)  # wait
>              client.loop_stop()  # stop the loop
>              print("Device added" + "\n")

This is a local name, local to the method.

>              listofdevice = []
>              listofdevice.append(self.fileName_UI)
>              print(listofdevice)

You could store the list in a file: read the current list from the file 
and then write the modified list to the file. The file won't exist 
initially, so you can treat that as the list being empty.

You're already importing the json module, so you could read/write it as 
JSON.

Also, _don't_ use a "bare" except like here:

>          except:

because catches _all_ exceptions. Instead, catch only those you're 
prepared to handle.

[snip]



More information about the Python-list mailing list