Help needed urgently for running some code!!!!

Spencer Du spencerdu at hotmail.co.uk
Mon Sep 2 11:05:14 EDT 2019


Hi

I want to execute 

"from devicesEmbedded import *": in GUI.py after all code in GUI.py is run. Also how do I make the devicesEmbedded.py reload and run when a txt file is created in the name of "list_of_devices.txt" in the GUI.py python program.


GUI.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from mqtt import *
# from devicesEmbedded import *
import json

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self,parent = None):
        QMainWindow.__init__(self)
        super(MainWindow, self).__init__(parent)
        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)

        self.setMinimumSize(QSize(800, 600))
        self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com")

        pybutton = QPushButton('Add device', self)

        pybutton.clicked.connect(self.importbutton)

        pybutton.move(100, 400)
        pybutton.resize(150, 32)

        self.textbox = QLineEdit(self)
        self.textbox.move(100,350)
        self.textbox.resize(100, 32)
        
        self.fileName_UI = ""

    def importbutton(self):
        self.fileName_UI = self.textbox.text()
        self.loadGUI()

    def getGUIFilename(self):
        return self.fileName_UI

    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/list_of_devices")
            client.publish("microscope/light_sheet_microscope/UI/list_of_devices", 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")

            client.run()
            client.loop_start()
            time.sleep(2)
            print("Subscribing to topic", "microscope/light_sheet_microscope/UI/list_of_devices")
            client.subscribe("microscope/light_sheet_microscope/UI/list_of_devices")
            print("Publishing message to topic", "microscope/light_sheet_microscope/UI/list_of_devices")
            client.publish("microscope/light_sheet_microscope/UI/list_of_devices", self.fileName_UI + " added to device list")
            time.sleep(1)
            client.loop_stop()

            listofdevices = []
            listofdevices.append(self.fileName_UI)
            with open("list_of_devices.txt", "a+") as myfile:
                for item in listofdevices:
                    myfile.write(item + ",")
                    
                    
                    print(item)
            print(listofdevices)
            print("Device added to list")
        except:
            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}}, indent=2))
            time.sleep(2)  # wait
            client.loop_stop()  # stop the loop
            print(device_message + ".py " + "file doesn't exist")
            print("Device not added")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    a = mainWin.show()
    try:
        mainWin.show()
        os.remove("list_of_devices.txt")
        print("Awaiting devices to be launched")
    except:
        print("Awaiting devices to be launched")
    publishedMessage = mainWin.getGUIFilename()
    sys.exit(app.exec_())

devicesEmbedded.py:

import random
import asyncio
from actorio import Actor, Message, DataMessage, ask, EndMainLoop, Reference
from mqtt import *
# from GUI import *

client = device("Device")
client.run()
client.loop_start()
time.sleep(1)

print("Subscribing to topic", "microscope/light_sheet_microscope/UI/list_of_devices")
client.subscribe("microscope/light_sheet_microscope/UI/list_of_devices")
client.loop_stop()  # stop the loop
                 
def readFile(fname):
	try:
		with open(fname, "r") as f:
			for item in f:
				print(item)
	except:
		print("No devices added yet")
readFile("list_of_devices.txt")

mqtt.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic

class device(mqtt.Client):
    def on_connect(self, mqttc, obj, flags, rc):
        if rc == 0:
            print("Connected to broker")
        else:
            print("Connection failed")

        # mqttc.subscribe("microscope/light_sheet_microscope/UI")

    def on_message(self, mqttc, userdata, message):
        msg = str(message.payload.decode("utf-8"))
        print("message recieved= " + msg)
        # print("File which you want to import(with .py extension)")
        print("message topic=", message.topic)
        print("message qos=", message.qos)
        print("message retain flag=", message.retain)

    def run(self):
        self.connect("broker.hivemq.com", 1883, 60)

Thanks



More information about the Python-list mailing list