59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
|
import os, sys, imp, re
|
||
|
|
||
|
class PythonQuirks(object):
|
||
|
def __init__(self):
|
||
|
self.home = os.getcwd()
|
||
|
self.quirks = {}
|
||
|
self.last = {}
|
||
|
self.load()
|
||
|
|
||
|
def load(self):
|
||
|
self.last = self.quirks.copy()
|
||
|
self.quirks.clear()
|
||
|
filenames = []
|
||
|
if not os.path.exists(os.path.join(self.home, 'quirks')):
|
||
|
os.mkdir(os.path.join(self.home, 'quirks'))
|
||
|
for fn in os.listdir(os.path.join(self.home, 'quirks')):
|
||
|
if fn.endswith('.py') and not fn.startswith('_'):
|
||
|
filenames.append(os.path.join(self.home, 'quirks', fn))
|
||
|
|
||
|
modules = []
|
||
|
for filename in filenames:
|
||
|
name = os.path.basename(filename)[:-3]
|
||
|
try: module = imp.load_source(name, filename)
|
||
|
except Exception, e:
|
||
|
print "Error loading %s: %s (in pyquirks.py)" % (name, e)
|
||
|
else:
|
||
|
if hasattr(module, 'setup'):
|
||
|
module.setup()
|
||
|
self.register(vars(module))
|
||
|
modules.append(name)
|
||
|
for k in self.last:
|
||
|
if k in self.quirks:
|
||
|
if self.last[k] == self.quirks[k]:
|
||
|
del self.quirks[k]
|
||
|
|
||
|
if self.quirks:
|
||
|
print 'Registered quirks:', '), '.join(self.quirks) + ")"
|
||
|
else:print "Warning: Couldn't find any python quirks"
|
||
|
|
||
|
def register(self, variables):
|
||
|
for name, obj in variables.iteritems():
|
||
|
if hasattr(obj, 'command'):
|
||
|
try:
|
||
|
if not isinstance(obj("test"), basestring):
|
||
|
raise Exception
|
||
|
except:
|
||
|
print "Quirk malformed: %s" % (obj.command)
|
||
|
else:
|
||
|
self.quirks[obj.command+"("] = obj
|
||
|
|
||
|
def funcre(self):
|
||
|
if not self.quirks:
|
||
|
return r""
|
||
|
f = r"("
|
||
|
for q in self.quirks:
|
||
|
f = f + q[:-1]+r"\(|"
|
||
|
f = f + r"\)|\\[0-9]+)"
|
||
|
return f
|