Fi: Code

Here are all the scripts used in this project:

motherpython.py
The main script.

# from test import *
# test_func() #prints 'Hello'
# print (myvar)      #prints 42

import pkgutil
import sys
from twisted.internet import task
from twisted.internet import reactor
from Tkinter import *
import threading

class App(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def callback(self):
        Log("Destroying GUI...", 'warning')
        self.root.destroy()
        
    def run(self):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)
        l = Label(self.root,text="HAS", font=("Helvetica", 43))
        l.pack()
        self.root.mainloop()
            
# Terminal colour values
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    
#
# Log
#
# msg: Message
# msg_type: info, warning, error, ok, bold...
def Log(msg, msg_type = 'info'):
    switcher = {
        'info': '',
        'warning': bcolors.WARNING,
        'error': bcolors.FAIL,
        'okblue': bcolors.OKBLUE,
        'okgreen': bcolors.OKGREEN,
        'ok': bcolors.OKGREEN,
        'bold': bcolors.BOLD,
        'b': bcolors.BOLD,
    }
    print(switcher.get(msg_type, 'info') + msg + bcolors.ENDC)
    
#
# Load all modules
#
modules = []
def LoadAllModulesFromDir(dirname):
    Log('Loading modules...', 'bold')
    for importer, package_name, _ in pkgutil.iter_modules([dirname]):
        full_package_name = '%s/%s' % (dirname, package_name)
        if full_package_name not in sys.modules:
            Log('Loading and adding module ' + full_package_name + ' to the list of modules...')
            module = importer.find_module(package_name
                        ).load_module(full_package_name)
                        
            # Verify module
            if CheckModuleIntegrity(module) == False:
                continue
            
            modules.append(module)
            # Start module
            module.Start()
            # Schedule module
            looping_call = task.LoopingCall(module.Update)
            looping_call.start(module.config.get('update_freq'))
            # Load GUI
            body_frame = Frame()
            # Title bar
            title_frame = Frame()
            l = Label(title_frame,text=module.config.get('title'), font=("Helvetica", 24))
            l.pack()
            button1 = Button(title_frame, text = 'Quit ' + module.config.get('title'), width = 25, command= lambda: CloseModule(module, title_frame, body_frame, looping_call))
            button1.pack()
            title_frame.pack()
            # Module's custom GUI
            module.OnGui(body_frame)
            # Done!
            Log('Module ' + module.__name__ +  'successfully added and loaded.', 'okblue')


#
# Reload modules
#
def ReloadModules():
    Log('Reloading modules...', 'bold')
    for mod in modules:
        Log('Loading module '' + mod.__name__ + ''...')
        mod.Start()
        Log('Module ' + mod.__name__ + ' successfully reloaded.', 'okblue')


#
# Code that runs after setup
#
def StartUpdateSchedule():
    Log('Running update... Cancel anytime with Ctrl + C.', 'warning')
    # Run update schedule
    reactor.run()
    
# Private.
# Close module.
#
def CloseModule(ref_module, title_frame, body_frame, looping_call):
    Log("Closing module '" + ref_module.config.get('name') + "'...")
    
    body_frame.pack_forget()
    body_frame.destroy()
    
    l = Label(title_frame,text="Closing...", font=("Helvetica", 20))
    l.pack()
    title_frame.pack()
            
    ref_module.Closed()
    
    looping_call.stop()
    
    title_frame.pack_forget()
    title_frame.destroy()
    
    Log("Module '" + ref_module.config.get('name') + "' successfully closed.")

def CheckModuleIntegrity(ref_module):
    config = ref_module.config
    if isinstance(config.get('name'), str) == False:
        Log("Module doesn't have a name.", 'error')
        return False
    
    if isinstance(config.get('title'), str) == False:
        Log("Module doesn't have a title.", 'error')
        return False
        
    if isinstance(config.get('update_freq'), float) == False:
        Log("Module doesn't know how often it wants to be called.", 'error')
        return False
        
    return True
#
# This code runs first
#

app = App()
app.start()

LoadAllModulesFromDir('Modules')
StartUpdateSchedule()

Modules/template.py
A template for creating modules.

from Tkinter import *

# Configuration
config = dict(
    name = 'sample',
    title = 'Sample',
    version = '1',
    publisher = 'Rockbutton',
    home_url = 'http://rockbutton.tk/has',
    support_url = 'http://rockbutton.tk/has/support',
    update_freq = 60.0 # Sixty seconds
)

#
# This function gets called when the module loads.
#
def Start():
    print("Module started!")

#
# This function gets called every [update_freq] seconds.
#
runs = 0
def Update():
    global runs
    print("This is run #%d" % runs)
    runs += 1
    
#
# Use this function to fill your part of the GUI.
#
def OnGui(module_frame):
    module_frame.pack()

#
# This function is called when the user closes the module.
#
def Closed():
    print("I'm dead, Jim!")

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s