No error when I start the script and but the callback of the class startSacnRec doesn't work and Visual Code give me the info "Callback is not accessed"
class sacnRec():
#contstruktur super().__init__(self) Elternklasse vererbung aufrufen
def __init__(self, fileName, universum):
self.fileName = fileName
self.universum = universum
def deleteFile(self):
with open(self.fileName + '.txt','w'): pass
def packettoIntData(data):
uniData = str(data)[1:-1]
uniDataList = [int(s) for s in uniData.split(',')]
return uniDataList
def writeCsv(set,data,fileName):
with open(fileName + '.txt', "a") as file:
file.write(str(set))
file.write(str(data))
def startSacnRec(self):
print("Start des Servers" + str(self.universum))
receiver = sacn.sACNreceiver()
receiver.start()
#receiver.listen_on('universe', universe=self.universum) # listens on universe 1
def callback(packet): # packet type: sacn.DataPacket
print(packet.dmxData)
print(packet.sourceName)
print("test")
#uniOneSet = [int(packet.universe),int(packet.priority),str(packet.sourceName) ]
#print(uniOneSet)
# uniOneDmx = packettoIntData(packet.dmxData)
#writeCsv(uniOneSet,uniOneDmx, name)
receiver.join_multicast(1)
time.sleep(10) # receive for 10 seconds
receiver.stop()
one = sacnRec(1,1)
one.startSacnRec()
I think the problem is here
enter image description here
Using a decorator (the #receiver.listen_on... part) is usually for class methods.
If you want to use a closure based callback, then use receiver.register_listener approach.
https://github.com/Hundemeier/sacn#receiving-1
Related
Link for my initial part of this question
I am new to object-oriented programming I need to write a BankDataWriterBase base class in the following program using the class diagram given in below to the code. I cannot understand the complete thing that the class diagram has, anybody here to know & explain to me what they actually saying using the class diagram
After my understanding I have done like this :
I know my approach is wrong but i don't know where the mistake happening
import pandas as pd
class ExcelParser:
def __init__(self):
self.config = []
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None, na_values= None, keep_default_na=False)
return [x for k, v in raw_excel.items() for x in v[v.columns.intersection(conf)].to_dict(orient='records')]
class BankDataWriterBase:
def __init__(self):
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name):
res = True
return res
if __name__ == "__main__":
conf = list(input("ENTER THE LIST HERE : ").split(','))
file_name = input("Enter the full input path here : ")
out_path = input("Enter the full path for the output : ")
bank_id = input("Enter the Bank ID : ")
obj = ExcelParser()
obj.config = conf
print(obj.extract(file_name))
obj1 = BankDataWriterBase()
obj1.output_path = out_path
obj1.bank_identifier = bank_id
print(obj1.write_file(file_name))
After seeing some of the answers i changed my code like the following
import pandas as pd
class ExcelParser:
def __init__(self):
self.config = []
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None, na_values= None, keep_default_na=False)
return [x for k, v in raw_excel.items() for x in v[v.columns.intersection(conf)].to_dict(orient='records')]
class BankDataWriterBase:
def __init__(self,file_name,out_path,bank_id):
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name:str):
res = True
return res
class BankDataWriterImpl(BankDataWriterBase):
def __init__(self, file_name, out_path, bank_id):
super().__init__(file_name, out_path, bank_id)
def extrac_json(self, file_name):
pass
if __name__ == "__main__":
conf = list(input("ENTER THE LIST HERE : ").split(','))
file_name = input("Enter the full input path here : ")
out_path = input("Enter the full path for the output : ")
bank_id = input("Enter the Bank ID : ")
obj = ExcelParser()
obj.config = conf
print(obj.extract(file_name))
obj1 = BankDataWriterBase()
obj1.output_path = out_path
obj1.bank_identifier = bank_id
print(obj1.write_file(file_name))
What they mean is that BankDataWriterImpl should inherit from BankDataWriterBase like so :
class BankDataWriterBase():
...
class BankDataWriterImpl(BankDataWriterBase):
# this class inherit from parent class BankDataWriterBase
# when a `BankDataWriterBase` object is created, parent.__init__ method is executed.
def extract_jon(self, filename: str):
pass
then in driver code, you can create a BankDataWriterImpl() object instead of the BankDataWriterBase() as you did.
It will inherit its __init__ method from parent and have a new extract_json method.
Another problem you didn't mention come from BankDataWriterBase attributes. Your code assume the existance of 3 global variables.
They should be passed to the class when you create the object, like so :
But watchout when creating a BankSomething object, since those arguments are now expected :
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
obj1 = BankDataWriterImpl(input_path, output_path, bank_identifier)
Edit after comment : but my lead said write class only for BankDataWriterBase()
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
def write_file(file_name: str):
pass
obj = BankDataWriterBase(input_path, output_path, bank_identifier)
# setattr add a new attribute to `obj`, first argument is the object,
# second argument its name (obj.name)
# third argument the attribute itself
# here we attach a new method `obj.write_file` to the object
setattr(obj, 'write_file', write_file)
# now you can use it like that :
# this line would have raised an exception before the `setattr` line
obj.write_file("correct_file_path")
the structure without implementations:
class Task:
def __init__(self): # initialise all the instance variables (None in this case)
pass # this this might need to be empty
def run(self) -> None:
pass
class BankDataWriterBase:
def __init__(self, file_name: str, out_path: str, bank_id: str):
# you might wan't to set default values: file_name: str = "" for example
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name) -> str:
pass
class BankDataWriterImpl(BankDataWriterBase):
# inherit from BankDataWriterBase, all functions and variables from BankDataWriterBase are now callable from this class
# as said in the other answer, this will be inherited so you don't need to have this
def __init__(self, file_name: str, out_path: str, bank_id: str):
super().__init__(file_name, out_path, bank_id) # call __init__ method of all the superclasses (in this case only BankDataWriterBase)
def extract_json(self, filename: str):
pass
I got a function run(self) and inside that function I was to open a file. I then want to close that file inside another function, reset(self).
This is my class:
class Heater (threading.Thread):
STATE_IDLE = "IDLE"
STATE_RUNNING = "RUNNING"
def __init__(self, simulate=False, time_step=config.sensor_time_wait):
threading.Thread.__init__(self)
self.daemon = True
self.simulate = simulate
self.time_step = time_step
self.reset()
if simulate:
self.temp_sensor = TempSensorSimulate(self, 0.5, self.time_step)
if sensor_available:
self.temp_sensor = TempSensorReal(self.time_step)
else:
self.temp_sensor = TempSensorSimulate(self,
self.time_step,
self.time_step)
self.temp_sensor.start()
self.start()
def reset(self):
self.profile = None
self.start_time = 0
self.runtime = 0
self.totaltime = 0
self.target = 0
def run(self):
now = datetime.datetime.now()
self.name = os.path.join('/storedata/store', "Date_" + now.strftime("%Y-%m-%d") + ".txt")
self.file = open(name, 'a')
self.file.write(now.strftime("%Y-%m-%d"))
reset()
would I just put self.file = self.run.file.close in reset(self) to achieve this?
I would do the following:
def __init__(self, simulate=False, time_step=config.sensor_time_wait):
self.file = None
now there is an attribute called file in your class. Set to None. Now
def __reset(self):
if self.file:
self.file.close()
self.file = None
that should do it ! Note that __reset is safe to call when the file isn't opened, since the file attribute exists and is None (closing an already closed file doesn't do anything, but still, it's clearer)
Note that this design only is interesting if you're using self.file somewhere else. Else don't define any member just do:
name = os.path.join(... // your code used "self.name" for some reason
with open(name, 'a') as file:
file.write(now.strftime("%Y-%m-%d"))
As a general rule, define class members only when necessary, and local variables anywhere else.
I have a question regarding a Python class I use in Blender. Basically, I wonder how the class works because some attributes are recorded without me specifically writing self.value = something. Here's the code:
class DialogOperator(bpy.types.Operator):
bl_idname = "object.dialog_operator"
bl_label = "Save/Load animation"
saving = bpy.props.BoolProperty(name="Save ? Else load.")
path_to_anim = bpy.props.StringProperty(name="Path to folder")
anim_name = bpy.props.StringProperty(name="Animation name:")
# path_to_anim += "/home/mehdi/Blender/Scripts/"
def execute(self, context):
# print('This is execute with: Saving: {} Name:{}'.format(self.saving, self.path_to_anim))
if self.saving:
self.launch_save()
message = 'Animation {} saved at {}'.format(self.anim_name, self.path_to_anim)
else:
self.launch_load()
message = 'Animation {} loaded'.format(self.anim_name)
self.report({'INFO'}, message)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def launch_load(self):
full_path = self.path_to_anim + self.anim_name
target_armature = Humanoid(bpy.data.objects['Armature'])
load_all(full_path, target_armature, 'LastLoaded')
def launch_save(self):
full_path = self.path_to_anim + self.anim_name
source_armature = Humanoid(bpy.data.objects['Armature'])
curves = source_armature.get_curves()
save_all(curves, source_armature,full_path)
Now, how come saving, path_to_anim and anim_name are considered as attributes (I'm able to call them in execute() and launch()) even though I did not write self.saving = saving
Thanks !
This is because saving,path_to_anim and anim_name are class attributes. They are defined for the class and not for a particular instance. They are shared among the instances. Here is a link for further explanation class-instance-attributes-python
i have a code below
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer, MicrophoneRecognizer
djv = Dejavu(config)
Recognize audio from a file
song = djv.recognize(FileRecognizer, "mp3/Sean-Fournier--Falling-For-You.mp3")
below is from dejavu/recognize.py
class BaseRecognizer(object):
def __init__(self, dejavu):
self.dejavu = dejavu
self.Fs = fingerprint.DEFAULT_FS
def _recognize(self, *data):
matches = []
for d in data:
matches.extend(self.dejavu.find_matches(d, Fs=self.Fs))
return self.dejavu.align_matches(matches)
def recognize(self):
pass # base class does nothing
class FileRecognizer(BaseRecognizer):
def __init__(self, dejavu):
super(FileRecognizer, self).__init__(dejavu)
def recognize_file(self, filename):
frames, self.Fs, file_hash = decoder.read(filename, self.dejavu.limit)
t = time.time()
match = self._recognize(*frames)
t = time.time() - t
if match:
match['match_time'] = t
return match
def recognize(self, filename):
return self.recognize_file(filename)
I don't undersand how recognize takes class Filereognizer and also filename where recognizer is defined as
def recognize(self, filename):
and takes only filename as a parameter. can someone explain how this work and what it actually does???
thanks to #daniel here is my follow up question
def recognize(self, recognizer, *options, **kwoptions):
r = recognizer(self)
return r.recognize(*options, **kwoptions)
this is recognizer under Djavu class and I am thinking "self" from line "r = recognizer(self)" is what make recognizer(under Dejavu class) can receive FileRecognizer class as a parameter right?
this is from dejavu(audiofingerprint software) github and link is below :
https://github.com/worldveil/dejavu
I am using pickle to save an object graph by dumping the root. When I load the root it has all the instance variables and connected object nodes. However I am saving all the nodes in a class variable of type dictionary. The class variable is full before being saved but after I unpickle the data it is empty.
Here is the class I am using:
class Page():
__crawled = {}
def __init__(self, title = '', link = '', relatedURLs = []):
self.__title = title
self.__link = link
self.__relatedURLs = relatedURLs
self.__related = []
#property
def relatedURLs(self):
return self.__relatedURLs
#property
def title(self):
return self.__title
#property
def related(self):
return self.__related
#property
def crawled(self):
return self.__crawled
def crawl(self,url):
if url not in self.__crawled:
webpage = urlopen(url).read()
patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel="canonical" href="([^"]*)" />')
patFinderRelated = re.compile('<li><a href="([^"]*)"')
findPatTitle = re.findall(patFinderTitle, webpage)
findPatLink = re.findall(patFinderLink, webpage)
findPatRelated = re.findall(patFinderRelated, webpage)
newPage = Page(findPatTitle,findPatLink,findPatRelated)
self.__related.append(newPage)
self.__crawled[url] = newPage
else:
self.__related.append(self.__crawled[url])
def crawlRelated(self):
for link in self.__relatedURLs:
self.crawl(link)
I save it like such:
with open('medTwiceGraph.dat','w') as outf:
pickle.dump(root,outf)
and I load it like such:
def loadGraph(filename): #returns root
with open(filename,'r') as inf:
return pickle.load(inf)
root = loadGraph('medTwiceGraph.dat')
All the data loads except for the class variable __crawled.
What am I doing wrong?
Python doesn't really pickle class objects. It simply saves their names and where to find them. From the documentation of pickle:
Similarly, classes are pickled by named reference, so the same
restrictions in the unpickling environment apply. Note that none of
the class’s code or data is pickled, so in the following example the
class attribute attr is not restored in the unpickling environment:
class Foo:
attr = 'a class attr'
picklestring = pickle.dumps(Foo)
These restrictions are why picklable functions and classes must be
defined in the top level of a module.
Similarly, when class instances are pickled, their class’s code and
data are not pickled along with them. Only the instance data are
pickled. This is done on purpose, so you can fix bugs in a class or
add methods to the class and still load objects that were created with
an earlier version of the class. If you plan to have long-lived
objects that will see many versions of a class, it may be worthwhile
to put a version number in the objects so that suitable conversions
can be made by the class’s __setstate__() method.
In your example you could fix your problems changing __crawled to be an instance attribute or a global variable.
By default pickle will only use the contents of self.__dict__ and not use self.__class__.__dict__ which is what you think you want.
I say, "what you think you want" because unpickling an instance should not mutate class level sate.
If you want to change this behavior then look at __getstate__ and __setstate__ in the docs
For anyone interested, what I did was make a superclass Graph which contained an instance variable __crawled and moved my crawling functions into Graph. Page now only contains attributes describing the page and its related pages. I pickle my instance of Graph which contains all my instances of Page. Here is my code.
from urllib import urlopen
#from bs4 import BeautifulSoup
import re
import pickle
###################CLASS GRAPH####################
class Graph(object):
def __init__(self,roots = [],crawled = {}):
self.__roots = roots
self.__crawled = crawled
#property
def roots(self):
return self.__roots
#property
def crawled(self):
return self.__crawled
def crawl(self,page,url):
if url not in self.__crawled:
webpage = urlopen(url).read()
patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel="canonical" href="([^"]*)" />')
patFinderRelated = re.compile('<li><a href="([^"]*)"')
findPatTitle = re.findall(patFinderTitle, webpage)
findPatLink = re.findall(patFinderLink, webpage)
findPatRelated = re.findall(patFinderRelated, webpage)
newPage = Page(findPatTitle,findPatLink,findPatRelated)
page.related.append(newPage)
self.__crawled[url] = newPage
else:
page.related.append(self.__crawled[url])
def crawlRelated(self,page):
for link in page.relatedURLs:
self.crawl(page,link)
def crawlAll(self,obj,limit = 2,i = 0):
print 'number of crawled pages:', len(self.crawled)
i += 1
if i > limit:
return
else:
for rel in obj.related:
print 'crawling', rel.title
self.crawlRelated(rel)
for rel2 in obj.related:
self.crawlAll(rel2,limit,i)
def loadGraph(self,filename):
with open(filename,'r') as inf:
return pickle.load(inf)
def saveGraph(self,obj,filename):
with open(filename,'w') as outf:
pickle.dump(obj,outf)
###################CLASS PAGE#####################
class Page(Graph):
def __init__(self, title = '', link = '', relatedURLs = []):
self.__title = title
self.__link = link
self.__relatedURLs = relatedURLs
self.__related = []
#property
def relatedURLs(self):
return self.__relatedURLs
#property
def title(self):
return self.__title
#property
def related(self):
return self.__related
####################### MAIN ######################
def main(seed):
print 'doing some work...'
webpage = urlopen(seed).read()
patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel="canonical" href="([^"]*)" />')
patFinderRelated = re.compile('<li><a href="([^"]*)"')
findPatTitle = re.findall(patFinderTitle, webpage)
findPatLink = re.findall(patFinderLink, webpage)
findPatRelated = re.findall(patFinderRelated, webpage)
print 'found the webpage', findPatTitle
#root = Page(findPatTitle,findPatLink,findPatRelated)
G = Graph([Page(findPatTitle,findPatLink,findPatRelated)])
print 'crawling related...'
G.crawlRelated(G.roots[0])
G.crawlAll(G.roots[0])
print 'now saving...'
G.saveGraph(G, 'medTwiceGraph.dat')
print 'done'
return G
#####################END MAIN######################
#'http://medtwice.com/am-i-pregnant/'
#'medTwiceGraph.dat'
#G = main('http://medtwice.com/menopause-overview/')
#print G.crawled
def loadGraph(filename):
with open(filename,'r') as inf:
return pickle.load(inf)
G = loadGraph('MedTwiceGraph.dat')
print G.roots[0].title
print G.roots[0].related
print G.crawled
for key in G.crawled:
print G.crawled[key].title
Using dill can solve this problem.
dill package: https://pypi.python.org/pypi/dill
reference: https://stackoverflow.com/a/28543378/6301132
According Asker's code, into this:
#notice:open the file in binary require
#save
with open('medTwiceGraph.dat','wb') as outf:
dill.dump(root,outf)
#load
def loadGraph(filename): #returns root
with open(filename,'rb') as inf:
return dill.load(inf)
root = loadGraph('medTwiceGraph.dat')
I wrote another example:
#Another example (with Python 3.x)
import dill
import os
class Employee:
def __init__ (self ,name='',contact={}) :
self.name = name
self.contact = contact
def print_self(self):
print(self.name, self.contact)
#save
def save_employees():
global emp
with open('employees.dat','wb') as fh:
dill.dump(emp,fh)
#load
def load_employees():
global emp
if os.path.exists('employees.dat'):
with open('employees.dat','rb') as fh:
emp=dill.load(fh)
#---
emp=[]
load_employees()
print('loaded:')
for tmpe in emp:
tmpe.print_self()
e=Employee() #new employee
if len(emp)==0:
e.name='Jack'
e.contact={'phone':'+086-12345678'}
elif len(emp)==1:
e.name='Jane'
e.contact={'phone':'+01-15555555','email':'a#b.com'}
else:
e.name='sb.'
e.contact={'telegram':'x'}
emp.append(e)
save_employees()