I have a program that is aiming to take inputs from sensors and then act upon inputs from these sensors from some pre-defined rules that are stored and called within a class. I am having problems passing the variables that the sensors are defined as into the rules class. Where I get errors of 'Rules object has not attribute .rules_temperature. My code is below:
class myInterfaceKit():
__interfaceKit = None
def __init__(self ):
try:
self.__interfaceKit = InterfaceKit()
except RuntimeError as e:
print("Runtime Exception: %s" % e.details)
print("Exiting....")
exit(1)
def open(self):
try:
self.__interfaceKit.openPhidget()
except PhidgetException as e:
print("Phidget Exception %i: %s" % (e.code, e.details))
def getInterfaceKit(self):
return self.__interfaceKit
def getSensor(self, sensor):
return self.__interfaceKit.getSensorValue(sensor)
class sensors():
__sound = 0
__temperature = 0
__light = 0
__motion = 0
__dbName = ""
__interfaceKit = None
__connection = None
__rules = None
def __init__(self, theInterfaceKit, dbName):
self.__sound = 0
self.__temperature=0
self.__light=0
self.__motion=0
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__dbName = dbName
self.__interfaceKit = theInterfaceKit
self.__connection = sqlite3.connect('testing1.db', check_same_thread=False) ######
def interfaceKitAttached(self, e):
attached = e.device
print("InterfaceKit %i Attached!" % (attached.getSerialNum()))
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(0, 5)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(1, 35)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(2, 60)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(3, 200)
def sensorInputs(self, e):
temperature = (self.__interfaceKit.getSensor(0)*0.2222 - 61.111)
sound = (16.801 * math.log((self.__interfaceKit.getSensor(1))+ 9.872))
light = (self.__interfaceKit.getSensor(2))
motion = (self.__interfaceKit.getSensor(3))
# check temperature has changed - if yes, save and update
if temperature != self.__temperature:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__temperature = temperature
print("Temperature is: %i:" % self.__temperature)
self.writeToDatabase( 'temperature', self.__temperature, self.__strTimeStamp)
#check sound has changed - if yes, save and update
if sound != self.__sound:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__sound = sound
print("Sound is: %i " % self.__sound)
self.writeToDatabase( 'sound', self.__sound, self.__strTimeStamp )
#check light has changed - if yes, save and update
if light != self.__light:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__light = light
print("Light is: %i " % self.__light)
self.writeToDatabase( 'light', self.__light, self.__strTimeStamp )
if motion != self.__motion:
self.__motion = motion
print ("motion is %i" % self.__motion)
def openDatabase(self):
cursor = self.__connection.cursor()
cursor.execute("CREATE TABLE " + self.__dbName + " (sensor text, value text, time_stamp text)")
def writeToDatabase(self, sensorType, data, time):
cursor = self.__connection.cursor()
cursor.execute("INSERT INTO " + self.__dbName + " VALUES (?, ?, ?)", (sensorType, data, time))
self.__connection.commit()
def closeDatabase():
self.__connection.close()
def start(self):
try:
self.__interfaceKit.getInterfaceKit().setOnAttachHandler(self.interfaceKitAttached)
self.__interfaceKit.getInterfaceKit().setOnSensorChangeHandler(self.sensorInputs)
self.openDatabase()
except PhidgetException as e:
print("Phidget Exception %i: %s" % (e.code, e.details))
print("Exiting....")
exit(1)
This is where the problem lies:::
class Rules(sensors):
__tempLower=0
__tempUpper=0
def __init__(self):
self.__tempLower=28
self.__tempUpper=30
self.__temperature
def tempRule(self, sensors): ##Temperature rule
if self.__temperature == self.__tempLower:
print("testing")
phidgetInterface = myInterfaceKit()
phidgetInterface.open()
theSensors = sensors(phidgetInterface, "event156")
theSensors.start()
theRule = Rules()
theRule.tempRule()
chr = sys.stdin.read(1)
edit, error message:
Traceback (most recent call last):
File "H:\Project\Student\Prototype 1\eventProto.py", line 159, in
theRule = Rules()
File "H:\Project\Student\Prototype 1\eventProto.py", line 146, in init
self.__temperature
AttributeError: 'Rules' object has no attribute 'Rules_temperature'
Private members (starting with __) cannot be accessed by subclasses. (Well, they can be accessed using some hackery, but should not).
(see here)
In your case, __temperature is a private member of the base class sensors, but you're accessing it from the subclass Rules.
Replace the double underscore prefix with a single underscore (__temperature -> _temperature), and you're good to go.
Double underscore members are considered private, you have to prepend those with class name that defined said member.
Use these magic private members like this:
class sensors:
__temp = 42
assert sensors()._sensors__temp == 42
class Rules(sensors):
def test(self):
assert self._sensors__temp == 42
Rules().test()
Related
I have already written a simple python cmd program using the cmd module. However, I would like it to be modular. For Example, there would be a folder named script and any .py that contains a command would add the command to the application. How would I go about that?
NOTE:
I have figured out how to find and load modules that are within a folder using importlib.
First, you must understand how the cmd module works. I would not go into it here but the gist is command is entered, then split up into the actual command itself and its arguments. The command is then searched in the implementation of the cmd module using getattr(). The resulting function returned is then executed. Raises an error if the function(attribute) is not found.
Add the list of modules added to a list.
lst.append(importlib.importlib.import_module(<module path here>))
When cmd is finding a command, modify the code to get it to run through the list of imported modules and see if the function/command exists in that module. If so, execute it.
rough code to find func
def findfunc(funcname):
for module in lst:
if hasattr(<module class where func is stored>, "<funcname>"):
return getattr(<module class where func is stored>,"<funcname>")
However, I will leave my implementation here. It also includes the capability to reload modules(limited to a certain extent) and private commands that do not show up in help or autocomplete(I am using py prompt toolkit). A fair bit of warning, no docs or help in understanding this code as it is only meant for my personal use only. Meaning don't directly copy it and also It was a modification to the python cmd module.
import importlib
import os
import string
import sys
import time
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.styles import Style
from internal.logger import logger # my logger Implementation, ignore it
__all__ = ["cli2"]
PROMPT = '>>> '
IDENTCHARS = string.ascii_letters + string.digits + '_'
style = Style.from_dict(
{
"completion-menu.completion": "bg:#008888 #ffffff",
"completion-menu.completion.current": "bg:#00aaaa #000000",
"scrollbar.background": "bg:#88aaaa",
"scrollbar.button": "bg:#222222",
}
)
def parse(arg):
return arg.split()
class Interpreter:
identchars = IDENTCHARS
ruler = '='
lastcmd = ''
doc_leader = ""
doc_header = "Available Commands (type help <topic> to get documentation for <topic> ):"
misc_header = "Miscellaneous help topics:"
nohelp = "*** No help on %s"
use_rawinput = 1
modulelst = []
internalcmdlst = ["help", "exit", "reload", "listmodules", "listvar"]
def __init__(self, intro=None, prompt=PROMPT, stdin=None, stdout=None):
"""Instantiate a line-oriented interpreter framework.
The optional arguments stdin and stdout
specify alternate input and output file objects; if not specified,
sys.stdin and sys.stdout are used.
"""
self.prompt = prompt
self.intro = intro
if stdin is not None:
self.stdin = stdin
else:
self.stdin = sys.stdin
if stdout is not None:
self.stdout = stdout
else:
self.stdout = sys.stdout
self.cmdqueue = []
def cmdloop(self):
self.preloop()
try:
if self.intro:
self.stdout.write(str(self.intro) + "\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
line = self.session.prompt(self.prompt)
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
pass
def precmd(self, line):
"""Hook method executed just before the command line is
interpreted, but after the input prompt is generated and issued.
"""
# Parse command to argument
return self.parseline(line)
def postcmd(self, stop, line):
"""Hook method executed just after a command dispatch is finished."""
return stop
def preloop(self):
"""Hook method executed once when the cmdloop() method is called."""
self.autocommands = [item[3:] for item in self.get_names() if (item[-5:] != '__pvt') and (item[:3] == 'do_')]
self.session = PromptSession(completer=WordCompleter(self.autocommands, ignore_case=False))
def postloop(self):
"""Hook method executed once when the cmdloop() method is about to
return.
"""
self.autocommands, self.session = None, None
def parseline(self, line):
"""Parse the line into a command name and a string containing
the arguments. Returns a tuple containing (command, args, line).
'command' and 'args' may be None if the line couldn't be parsed.
"""
line = line.strip()
if not line:
return None, None, line
elif line[0] == '?':
line = 'help ' + line[1:]
elif line[0] == '!':
if hasattr(self, 'do_shell'):
line = 'shell ' + line[1:]
else:
return None, None, line
i, n = 0, len(line)
while i < n and line[i] in self.identchars: i = i + 1
cmd, arg = line[:i], line[i:].strip()
return cmd, arg, line
def onecmd(self, linecommand):
"""Interpret the argument as though it had been typed in response
to the prompt.
This may be overridden, but should not normally need to be;
see the precmd() and postcmd() methods for useful execution hooks.
The return value is a flag indicating whether interpretation of
commands by the interpreter should stop.
"""
cmd, arg, line = linecommand
if not line:
return self.emptyline()
if cmd is None:
return self.default(line)
self.lastcmd = line
if line == 'EOF':
self.lastcmd = ''
if cmd == '':
return self.default(line)
if cmd in self.internalcmdlst:
return self.getfunc(cmd)(arg)
else:
try:
terminalclass, func = self.getfunc(cmd)
except AttributeError:
return self.default(line)
return func(terminalclass, arg)
def emptyline(self):
"""Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty
command entered.
"""
if self.lastcmd:
return self.onecmd(self.lastcmd)
def default(self, line):
"""Called on an input line when the command prefix is not recognized.
If this method is not overridden, it prints an error message and
returns.
"""
self.stdout.write('*** Unknown syntax: %s\n' % line.split(" ")[0])
def get_names(self):
# This method used to pull in base class attributes
# at a time dir() didn't do it yet.
lst = [*dir(self.__class__)]
for modulejs in self.modulelst:
terminalclass = getattr(getattr(modulejs["module"], 'cli_helper'), "Terminal")
lst += dir(terminalclass)
return lst
def print_topics(self, header, cmds, maxcol):
if cmds:
self.stdout.write("%s\n" % str(header))
if self.ruler:
self.stdout.write("%s\n" % str(self.ruler * len(header)))
self.columnize(cmds, maxcol - 1)
self.stdout.write("\n")
def columnize(self, lst, displaywidth=80):
"""Display a list of strings as a compact set of columns.
Each column is only as wide as necessary.
Columns are separated by two spaces (one was not legible enough).
"""
if not lst:
self.stdout.write("<empty>\n")
return
nonstrings = [i for i in range(len(lst))
if not isinstance(lst[i], str)]
if nonstrings:
raise TypeError("list[i] not a string for i in %s"
% ", ".join(map(str, nonstrings)))
size = len(lst)
if size == 1:
self.stdout.write('%s\n' % str(lst[0]))
return
# Try every row count from 1 upwards
for nrows in range(1, len(lst)):
ncols = (size + nrows - 1) // nrows
colwidths = []
totwidth = -2
for col in range(ncols):
colwidth = 0
for row in range(nrows):
i = row + nrows * col
if i >= size:
break
x = lst[i]
colwidth = max(colwidth, len(x))
colwidths.append(colwidth)
totwidth += colwidth + 2
if totwidth > displaywidth:
break
if totwidth <= displaywidth:
break
else:
nrows = len(lst)
ncols = 1
colwidths = [0]
for row in range(nrows):
texts = []
for col in range(ncols):
i = row + nrows * col
if i >= size:
x = ""
else:
x = lst[i]
texts.append(x)
while texts and not texts[-1]:
del texts[-1]
for col in range(len(texts)):
texts[col] = texts[col].ljust(colwidths[col])
self.stdout.write("%s\n" % str(" ".join(texts)))
def addmodulesfromdirectory(self, directory):
try:
directory_contents = os.listdir(directory)
for item in directory_contents:
self.addmodule(os.path.join(directory, item), "".join([directory[2:], ".", item]))
except OSError as e:
print("Something Happened\nPlease try again :)")
logger.error("OSErrot, {}".format(e))
except ImportError as e:
print("Something Went Wrong while importing modules\nPlease try again :)")
logger.error("ImportError, {}".format(e))
except Exception as e:
print("Oops, my fault\nPlease try again :)")
logger.error("Exception, {}".format(e))
finally:
logger.info("Done importing cli modules")
def addmodule(self, pathdir, importdir):
if os.path.isdir(pathdir):
importedmodule = importlib.import_module(importdir)
modulejs = {
"module": importedmodule,
"name": importedmodule.__name__,
"importdir": importdir,
"pathdir": pathdir
}
self.modulelst.append(modulejs)
def removemodule(self, modulename):
if modulename in [x["name"] for x in self.modulelst]:
self.modulelst.remove(self.getmodulejs(modulename))
del sys.modules[modulename]
else:
raise ModuleNotFoundError
def replacemodule(self, modulename):
module = self.getmodulejs(modulename)
self.removemodule(modulename)
self.addmodule(module["pathdir"], module["importdir"])
def getmodulejs(self, modulename):
for i in self.modulelst:
if i['name'] == modulename:
return i
#staticmethod
def getmoduledep(modulename):
unsortedscriptsysmodules = [module for module in sys.modules if (("script" in module) and ("script" != module))]
sortedlst = []
for scriptmodules in unsortedscriptsysmodules:
mod = sys.modules[scriptmodules]
if not (hasattr(mod, "__path__") and getattr(mod, '__file__', None) is None) and (
scriptmodules != "script.{}".format(modulename)):
sortedlst.append(sys.modules[scriptmodules])
return sortedlst
def reloadmoduledep(self, modulename):
for dep in self.getmoduledep(modulename):
try:
importlib.reload(dep)
except ModuleNotFoundError as e:
print(e)
def getfunc(self, command):
if "do_" in command:
command = command[3:]
if command in self.internalcmdlst:
return getattr(self, "_".join(['do', command]))
else:
for modulejs in self.modulelst:
terminalclass = getattr(getattr(modulejs["module"], 'cli_helper'), "Terminal")
if hasattr(terminalclass, "_".join(['do', command])):
return terminalclass, getattr(terminalclass, "_".join(['do', command]))
raise AttributeError
def do_help(self, arg):
"""
List available commands with "help" or detailed help with "help cmd".
"""
if arg:
# XXX check arg syntax
try:
func = self.getfunc('help_' + arg)
except AttributeError:
try:
if arg[-5:] == '__pvt':
raise AttributeError
doc = self.getfunc('do_' + arg).__doc__
if doc:
self.stdout.write("%s\n" % str(doc))
return
except AttributeError:
pass
self.stdout.write("%s\n" % str(self.nohelp % (arg,)))
return
func()
else:
names = self.get_names()
cmds_doc = []
funchelp = {}
for name in names:
if name[:5] == 'help_':
funchelp[name[5:]] = 1
names.sort()
# There can be duplicates if routines overridden
prevname = ''
for name in names:
if name[:3] == 'do_' and name[-5:] != '__pvt':
if name == prevname:
continue
prevname = name
cmd = name[3:]
if cmd in funchelp:
cmds_doc.append(cmd)
del funchelp[cmd]
elif self.getfunc(name).__doc__:
cmds_doc.append(cmd)
self.stdout.write("%s\n" % str(self.doc_leader))
self.print_topics(self.doc_header, cmds_doc, 80)
self.print_topics(self.misc_header, list(funchelp.keys()), 80)
def do_exit(self, arg):
"""
Exit
"""
if arg:
print(self.prompt + "No arguments please")
print("Exiting")
time.sleep(1)
return True
def do_reload(self, arg):
if arg == "":
print("No Arguments found")
return
arg = parse(arg)
if arg[0] == "all":
localmodulelst = self.modulelst.copy()
self.modulelst = []
for i in localmodulelst:
print("Reloading", ".".join(i["name"].split(".")[1:]))
importlib.invalidate_caches()
self.reloadmoduledep(i["name"])
self.addmodule(i["pathdir"], i["importdir"])
self.autocommands = [item[3:] for item in self.get_names() if
(item[-5:] != '__pvt') and (item[:3] == 'do_')]
self.session = PromptSession(completer=WordCompleter(self.autocommands, ignore_case=False))
else:
print("Only argument \'all\' is accepted")
def do_listmodules(self, arg):
arg = parse(arg)
if arg[0] == "sys":
for i in sys.modules:
print(i)
elif len(arg) != 0:
print("No Argument Please")
else:
print("Listing all imported Modules")
for i in self.modulelst:
print(".".join(i["module"].__name__.split(".")[1:]))
If I have a case where I have a simple logging function in my main file:
def log_events(data_to_log):
log_this = '%s - %s' % (strftime("%Y-%m-%d %H:%M:%S"), data_to_log)
print ('%s\r' % log_this[0:140])
hlog_file = open('%s' % LOG_FILE_NAME, 'a')
print ( log_this, file=hlog_file)
hlog_file.close()
I have different classes for different tasks. I want to reuse the same log function in every class i make. This is in a file called. doit.py
class DoStuff:
def __init__ (self, extra_stuff_):
self.some_extra_stuff = extra_stuff
def do_the_thing(self):
x = 1
log_events( ' x is currently %s' % x )
x = 2
log_events( ' x is currently %s' % x )
log_events( ' extra stuff is %s' % self.some_extra_stuff )
Now the final code:
import doit
def log_events(data_to_log):
log_this = '%s - %s' % (strftime("%Y-%m-%d %H:%M:%S"), data_to_log)
print ('%s\r' % log_this[0:140])
hlog_file = open('%s' % LOG_FILE_NAME, 'a')
print ( log_this, file=hlog_file)
hlog_file.close()
things_i_want_to_do = doit.DoStuff('this is the stuff')
things_i_want_to_do.do_the_thing()
I get:
NameError: name 'log_events' is not defined
Is there a better way of sharing that log_events function with all the imported classes?
I have made a small class to open a serial port (ttyUSB0) on python, but when I try to run it as main it gives me back a whole lot of stuff I really don't know.
I want the class to create a Serial port instance when I run it and have the propper functions (or methods) give me back what I ask them to with the classe's instance. instead I'm getting the output below when I run:
$ python3 entrada.py
How do I make it run as I intend it to?
Here's the code for entrada.py
import serial #for port opening
import sys #for exceptions
from collections import __main__
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=5):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Open the serial port.'''
self.port.open()
def close(self):
''' Close the serial port.'''
self.port.close()
def send(self, msg):
self.prot.write(msg)
def recv(self):
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
def main():
test_port = Serializer(port = PORT)
try:
test_port().open()
except:
print ("Could not open serial port: ", sys.exc_info()[0])
sys.exit(2)
while True:
print(test_port.recv())
if __name__ == __main__:
main()
and here's the output:
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Point(tuple):
'Point(x, y)'
__slots__ = ()
_fields = ('x', 'y')
def __new__(_cls, x, y):
'Create new instance of Point(x, y)'
return _tuple.__new__(_cls, (x, y))
#classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(x=%r, y=%r)' % self
#property
def __dict__(self):
'A new OrderedDict mapping field names to their values'
return OrderedDict(zip(self._fields, self))
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return self.__dict__
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
return None
x = _property(_itemgetter(0), doc='Alias for field number 0')
y = _property(_itemgetter(1), doc='Alias for field number 1')
Point: x= 3.000 y= 4.000 hypot= 5.000
Point: x=14.000 y= 0.714 hypot=14.018
Point(x=100, y=22)
Point3D(x, y, z)
TestResults(failed=0, attempted=66)
Thanks for the help.
if __name__ == "__main__":
do_it()
im suprised if __name__ == __main__: didnt give you an error about undefined __main__
FYI, you misspelled port in self.prot.write(msg) to self.port.write(msg)
What is not running? what errors is it giving? how is that an output?
Why are you doing sys.exit(2)? A simple sys.exit() should suffice.
Also, having your variable as PORT for PORT = '/dev/ttyUSB0' may mix up with test_port = Serializer(port = PORT) in your main() function.
I'm making a form which allows me to add questions to a database. I've written code but when I try it I get this error ('AttributeError: 'module' object has no attribute 'GetTable')
The error lies with this part of my code 't = self.dbu.GetTable()'
#QtCore.pyqtSignature("on_add_btn_clicked()")
def Add_btn(self):
Question = self.Question_lineEdit.text()#Grabs the text from all line edit fields
Answer = self.Answer_lineEdit.text()
IsmultiChoice = self.IsMultiChoice_lineEdit.text()
if not Question:
QtGui.QMessageBox.warning(self, 'Warning', 'Username Missing')
else:
t = self.dbu.GetTable()
print (t)
for col in t:
if Question == col[1]:
QtGui.QMessageBox.warning(self, 'Warning', 'Question Taken. :(')#Checks the database and warns if the database does exist
else:
self.dbu.AddEntryToTable (Question, Answer, isMultiChoice)
QtGui.QMessageBox.information(self, 'Success', 'User Added Successfully!')#If everythings is okay it adds the user
self.close()
Here is my database code:
import mysql.connector
from mysql.connector import errorcode
from datetime import datetime
class DatabaseUtility:
def __init__(self, database, Tablename,):
self.db = database
self.Tablename = Tablename
self.cnx = mysql.connector.connect(user = 'root',
password = '',
host = 'localhost')
self.cursor = self.cnx.cursor()
def ConnectToDatabase(self):
try:
self.cnx.database = self.db
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
self.CreateDatabase()
self.cnx.database = self.db
else:
print(err.msg)
def CreateDatabase(self):
try:
self.RunCommand("CREATE DATABASE %s DEFAULT CHARACTER SET 'utf8';" %self.db)
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
def GetTable(self):
self.Tablename()
return self.RunCommand("SELECT * FROM %s;" % self.Tablename)
def GetColumns(self):
return self.RunCommand("SHOW COLUMNS FROM %s;" % self.Tablename)
def RunCommand(self, cmd):
print ("RUNNING COMMAND: " + cmd)
try:
self.cursor.execute(cmd)
except mysql.connector.Error as err:
print ('ERROR MESSAGE: ' + str(err.msg))
print ('WITH ' + cmd)
try:
msg = self.cursor.fetchall()
except:
msg = self.cursor.fetchone()
return msg
def AddEntryToTable(self, Question, Answer,IsMultiChoice):
cmd = " INSERT INTO " + self.Tablename + " (Question, Answer, IsMultiChoice)"
cmd += " VALUES ('%s', '%s', '%s');" % (Question, Answer, IsMultiChoice)
self.RunCommand(cmd)
def __del__(self):#Deconstructer class
self.cnx.commit()
self.cursor.close()
self.cnx.close()
if __name__ == '__main__':
db = 'UsernamePassword_DB'
Tablename = 'questiontable'
dbu = DatabaseUtility(db, Tablename)
What am I doing wrong and how can I correct it?
I'd need to see some additional code to be sure (see my comment). But for now my guess is it has to do with how you first instantiate or reference the dbu variable/attribute. If all you did is import it from another file, because dbu is created in that file's main() (in the snippet you provided), that might be the issue. For example, this is incorrect:
from whatever import dbu # wrong
from whatever.main import dbu # Also wrong. In fact I don't think this would even work
Instead, import DatabaseUtility directly into the script, then instantiate dbu like :
from whatever import Database Utility
class SomeClass(object):
...
def startDB(self, db, Tablename):
self.dbu = DatabaseUtility(db, Tablename)
The reason I guess this is because the error message says module has no attribute, instead of mentioning the actual class. Here's an example of the error I would expect to see:
In [31]: class MyClass(object):
one = 1
....:
In [32]: myc = MyClass()
In [33]: myc.one
Out[33]: 1
In [34]: myc.two
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-34-4bae87671838> in <module>()
----> 1 myc.two
AttributeError: 'MyClass' object has no attribute 'two'
Notice how it says MyClass is the problem, not "module".
Potentially unrelated, you might want to remove self.Tablename() from DatabaseUtility.GetTable(). The way you have your class defined, Table is an attribute to the DatabaseUtility class, but by including the parentheses you're trying to call it as if it were a method (like GetTable is).
I am trying to save the object candle in the dictionary candlebuffer, however it gives me the error below. I am struggling; what is incorrect with my syntax?
class Observer:
def __init__(self):
self.listeners = []
def attach(self, listener):
if not listener in self.listeners:
self.listeners.append(listener)
def notify(self, event):
for listener in self.listeners:
listener.update(event)
class CandleGenerator(Observer):
def __init__(self,freq):
Observer.__init__(self)
self.freq = freq
self.candle = Candle()
def update(self,tick):
self.candle.addTick(tick,self.freq)
if keyfunc(self.candle.timestamp,self.freq) != self.candle.ref_timestamp:
self.notify(self.candle)
self.candle = Candle()
class CandlePrinter:
def update(self, candle):
print "Bougie>>>>>> freq: %s %s %s %s %s %s %s %s %s " % (candle.freq,candle.last_price,candle.volume, candle.timestamp, candle.ref_timestamp, candle.open_price,candle.high_price,candle.low_price, candle.last_price)
class CandleBuffer:
def __init__(self,candle):
self.candlebuffer={0: candle}
def update(self,candle):
self.candlebuffer[candle.timestamp]= candle
print self.candlebuffer
print('begin')
tickGenerator = TickGenerator()
candleGenerator1 = CandleGenerator(1)
candlePrinter = CandlePrinter()
candleBuffer = CandleBuffer(5)
tickGenerator.attach(candleGenerator1)
candleGenerator1.attach(candlePrinter)
candleGenerator1.attach(candleBuffer)
tickGenerator.generate()
It gives the following output:
TypeError: __init__() takes exactly 2 arguments (1 given)
Since you have confirmed what I was suspecting, you have to pass another argument to the constructor, and use a dictionary instead of a set:
class CandleBuffer():
def __init__(self,candle):
self.candlebuffer={0 : candle}
def update(self,candle):
self.candlebuffer[candle.timestamp]= candle
# ...
candleBuffer = CandleBuffer(a_candle)
candleBuffer.update(another_candle)
This isn't what cause your error but you need to use : to create a dictionary.
self.candlebuffer = { 0 : candle }
It's on the format key : value.
I guessing that you're creating a CandleBuffer without giving an argument somewhere else in your code.