I have created a singlton Here is the class description.
allsms.py
from DB.models import ApiKey,ServiceProvider
from DB.messagenet import MessageNet
class SMSMgr( object ):
_instance = None
_allsp = []
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls._instance :
cls._instance = super(SMSMgr, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def loadsettings(self):
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
#print self._allsp
def reload(self):
self._allsp = []
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
def send(self):
print "+++++++++++++++++++== Global send "
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
Now in test.py file of the same directory I am trying to use the singleton object which stored in the _allsp variable like.
from SMShandler.allsms import SMSMgr
b = SMSMgr()
#b.loadsettings()
print b._allsp
This is printing empty list. But when I am doing like this:
b = SMSMgr()
b.loadsettings()
print b._allsp
it is printing the list of objects .
My question is, if the above design is singlton then why print b._allsp is printing empty list in test.py? I am already loading loadsettings in the allsms.py file .
You are running loadsettings() in an if __name__ == "__main__" block:
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
The purpose of such a block is to happen only when the code is run directly (like python allsms.py). That means it won't happen when it is imported in the line:
from SMShandler.allsms import SMSMgr
If you put the line b.loadsettings() outside of the if block, you'll see that it will already be loaded.
Related
#these classes live inside exchanges/impl/tse/mixins.py
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
class SubParserMixin():
def __init__(self):
self.context = PacketContext()
def on_packet(self, packet):
self.context.capture_tstamp = packet.capture_timestamp
self.parse_er_data(packet.payload)
#this mock test lives in another python file
from exchanges.impl.tse.mixins import PacketContext
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp(self):
"""
test receive_timestamp is passed down correctly from PacketContext to on_packet()
"""
assert self.context.capture_tstamp == 1655417400314635000
I am trying to mock the self.capture_tstamp attribute in the PacketContext() class.
But in the above, I am getting an error that says
AssertionError: assert None == 1655417400314635000
E + where None = <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0>.capture_tstamp
E + where <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0> = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>.context
It seems very strange that the program is not recognising PacketContext().
You can make use of the patch.object decorator as below
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
<import_PacketContext_here>
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp():
test_instance = PacketContext()
assert test_instance.capture_tstamp == 1655417400314635000
I have an task to do to figure out what the code below does. it looks like it was constructed in python2 but I want to use python3. I have installed argparse which it requires and set up necessary file path but every time I run the program in command Line I get these issues.
Traceback (most recent call last):
File "C:\Users\Name\pythonScripts\Noddy.py", line 6, in <module>
class Noddy:
File "C:\Users\Name\pythonScripts\Noddy.py", line 63, in Noddy
if __name__ == '__main__': main()
File "C:\Users\Name\pythonScripts\Noddy.py", line 57, in main
ent = Noddy.make(fools)
NameError: name 'Noddy' is not defined
The code is below.
#! python3
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
#classmethod
def make(self, l):
ent = Noddy(l.pop(0))
for x in l:
ent.scrobble(x)
return ent
def scrobble(self, x):
if self.holder > x:
if self.ant is None:
self.ant = Noddy(x)
else:
self.ant.scrobble(x)
else:
if self.dec is None:
self.dec = Noddy(x)
else:
self.dec.scrobble(x)
def bubble(self):
if self.ant:
for x in self.ant.bubble():
yield x
yield self.holder
if self.dec:
for x in self.dec.bubble():
yield x
def bobble(self):
yield self.holder
if self.ant:
for x in self.ant.bobble():
yield x
if self.dec:
for x in self.dec.bobble():
yield x
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("foo")
args = ap.parse_args()
foo = open(args.foo)
fools = [int(bar) for bar in foo]
ent = Noddy.make(fools)
print(list(ent.bubble()))
print
print(list(ent.bobble()))
if __name__ == '__main__': main()
Your def main() and if __name__=='__main__' have been written inside your class. The interpreter tries to execute them while it is defining the class, and can't, because the class Noddy doesn't exist until the class definition is finished.
Fix the indentation so that the main stuff lies outside your class.
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
# other methods INSIDE the class
# ...
# Notice the indentation — this function is OUTSIDE the class
def main():
# whatever main is supposed to do
# ...
if __name__=='__main__':
main()
I wanted to run code placed inside of thing.process upon when I hit the command.processCommand object (when i'm looping through all of the commands placed inside of defined[]), is there a way I can achieve this? This aforementioned loop will be executed as is such in myproject.py
command.py
class Command:
global defined
defined = []
def __init__(self, name):
self.name = name
self.description = "This command lacks a description"
self.args = ""
self.process = None
defined.append(self)
eightball.py
def processCommand():
print('hello')
thing = commands.Command('8ball')
thing.description = "Gives you a response from the mighty 8ball."
thing.process = processCommand
myproject.py
# Cogs
import cogs.commands as commands
import cogs.eightball
import cogs.helloworld
def processCommands(message):
if(message.content[:2] == "b#"):
args = message.content.split(' ')
args[0] = args[0][2:]
for command in defined:
if args[0] == command.name:
command.args = args
command.processCommand
for x in defined:
if x.process: # to skip `self.process = None`
x.process()
EDIT: you need process() instead of processCommand
for command in defined:
if args[0] == command.name:
command.args = args
command.process()
I am new to python and I'm trying this code below q Objects1 return to list
how can I do this?
it returns me the following error
File "/ home/paulo/Desktop/testepy2/objectMIB.py", line 53
return
SyntaxError: 'return' outside function
thank you
from pysnmp.entity import engine, config
from pysnmp import debug
from pysnmp.entity.rfc3413 import cmdrsp, context, ntforg
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.smi import builder
import threading
import collections
import time
MibObject = collections.namedtuple('MibObject', ['mibName',
'objectType', 'valueFunc'])
class Mib(object):
"""Stores the data we want to serve.
"""
def __init__(self):
self._lock = threading.RLock()
self._test_count = 0
self._test_get = 10
self._test_set = 0
def getTestDescription(self):
return "My Description"
def getTestCount(self):
with self._lock:
return self._test_count
def setTestCount(self, value):
with self._lock:
self._test_count = value
def getTestGet(self):
return self._test_get
def getTestSet(self):
return self._test_set
def setTestSet(self):
self._test_set = value
class ListObejtc ():
mib = objectMIB.Mib()
objects1 = [MibObject('MY-MIB', 'testDescription', mib.getTestDescription),
MibObject('MY-MIB', 'testCount', mib.getTestCount),MibObject('MY-MIB', 'testGet', mib.getTestGet), MibObject('MY-MIB', 'testSet', mib.getTestSet) ]
print objects1
return
It's normal for the code you have shown nested inside "ListObejtc" to be in a method, like so:
class ListObejtc ():
def __init__(self):
pass
def doObjects(self):
mib = objectMIB.Mib()
objects1 = [MibObject('MY-MIB', 'testDescription', mib.getTestDescription),
MibObject('MY-MIB', 'testCount', mib.getTestCount),MibObject('MY-MIB', 'testGet', mib.getTestGet), MibObject('MY-MIB', 'testSet', mib.getTestSet) ]
print objects1
return objects1
You got a SyntaxError because the return as you had it was in class context, and it makes no sense there.
I thought the print statement just called the .write() method on the sys.stdout (by default) object.
but having written a subclass like this:
import time
class logfile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
def write(self, logstr):
if logstr[-1] != '\n': logstr += '\n'
super(logfile, self).write(time.strftime('%D-%T ') + str(logstr))
It seems to work if I create a logfile object and call the write method, but when trying to change the sys.stdout object to an instance of the logfile it appears as though print isn't calling write. Maybe writelines?
Using this:
#!/usr/bin/python
from myfile import logfile
import sys
sys.stdout = logfile('somefile', 'w')
print 'this is a test'
sys.stdout.write('this is another test')
My output file 'somefile' contains:
this is a test
08/10/11-16:59:47 this is another test
You can see the first line in the output file is what I tried to print and the second line is what was used in sys.stdout.write
I thought print just called the write method- clearly I'm missing something basic.
Apparently this is an limitation of the implementation of Python 2 where print is a statement rather than an expression with side-effects (as it is in Python 3).
I rewrote the code to something that works in Python 3:
from io import FileIO
import time
class logfile(FileIO):
def __init__(self, *args, **kwargs):
FileIO.__init__(self, *args, **kwargs)
def write(self, logstr):
if logstr[-1] == '\n': logstr = logstr[:-1]
super(logfile, self).write(bytes(time.strftime('%D-%T ') + str(logstr), 'UTF-8'))
import sys
sys.stdout = logfile('somefile', 'w')
print("This is a test")
sys.stdout.write('this is another test')
As far as I know there is no way to create the same behaviour in Python 2.
I also tried using from __future__ import print_function but that made no difference.
If you put the file in an instance variable, it seems to work.
import time
class logfile(object):
def __init__(self, *args, **kwargs):
self.f = file(*args, **kwargs)
def write(self, logstr):
if logstr[-1] != '\n': logstr += '\n'
self.f.write(time.strftime('%D-%T ') + str(logstr))
Unfortunately it logs extra empty lines, here is one solution (print '2', '3', '4' writes 3 entries):
class logfile(object):
def __init__(self, *args, **kwargs):
self.f = file(*args, **kwargs)
self.c = False
def write(self, logstr):
self.c = not self.c
if logstr[-1] != '\n': logstr += '\n'
if self.c:
self.f.write(time.strftime('%D-%T ') + str(logstr))
This one logs full lines (note: print "4\n", "5" is still 2 loglines):
class logfile(object):
def __init__(self, *args, **kwargs):
self.f = file(*args, **kwargs)
self.newline = True
def write(self, logstr):
if self.newline:
self.f.write(time.strftime('%D-%T '))
self.f.write(logstr)
self.newline = logstr[-1] == '\n'
Does anybody know how to handle full print statements in 1 loglines?
This article explains your problem. Basically if sys.stdout is a subclass of file then print bypasses sys.stdout.write and writes directly to sys.stdout.fd.
The solution to your problem is to use composition instead of subclassing file.