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.
Related
I have the following simple class definition:
def apmSimUp(i):
return APMSim(i)
def simDown(sim):
sim.close()
class APMSimFixture(TestCase):
def setUp(self):
self.pool = multiprocessing.Pool()
self.sims = self.pool.map(
apmSimUp,
range(numCores)
)
def tearDown(self):
self.pool.map(
simDown,
self.sims
)
Where class APMSim is defined purely by plain simple python primitive types (string, list etc.) the only exception is a static member, which is a multiprocessing manager.list
However, when I try to execute this class, I got the following error information:
Error
Traceback (most recent call last):
File "/home/peng/git/datapassport/spookystuff/mav/pyspookystuff_test/mav/__init__.py", line 77, in setUp
range(numCores)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
MaybeEncodingError: Error sending result: '[<pyspookystuff.mav.sim.APMSim object at 0x7f643c4ca8d0>]'. Reason: 'TypeError("can't pickle thread.lock objects",)'
Which is strange as thread.lock cannot be found anywhere, I strictly avoid any multithreading component (as you can see, only multiprocessing component is used). And none of these component exist in my class, or only as static member, what should I do to make this class picklable?
BTW, is there a way to exclude a black sheep member from pickling? Like Java's #transient annotation?
Thanks a lot for any help!
UPDATE: The following is my full APMSim class, please see if you find anything that violates it picklability:
usedINums = mav.manager.list()
class APMSim(object):
global usedINums
#staticmethod
def nextINum():
port = mav.nextUnused(usedINums, range(0, 254))
return port
def __init__(self, iNum):
# type: (int) -> None
self.iNum = iNum
self.args = sitl_args + ['-I' + str(iNum)]
#staticmethod
def create():
index = APMSim.nextINum()
try:
result = APMSim(index)
return result
except Exception as ee:
usedINums.remove(index)
raise
#lazy
def _sitl(self):
sitl = SITL()
sitl.download('copter', '3.3')
sitl.launch(self.args, await_ready=True, restart=True)
print("launching .... ", sitl.p.pid)
return sitl
#lazy
def sitl(self):
self.setParamAndRelaunch('SYSID_THISMAV', self.iNum + 1)
return self._sitl
def _getConnStr(self):
return tcp_master(self.iNum)
#lazy
def connStr(self):
self.sitl
return self._getConnStr()
def setParamAndRelaunch(self, key, value):
wd = self._sitl.wd
print("relaunching .... ", self._sitl.p.pid)
v = connect(self._getConnStr(), wait_ready=True) # if use connStr will trigger cyclic invocation
v.parameters.set(key, value, wait_ready=True)
v.close()
self._sitl.stop()
self._sitl.launch(self.args, await_ready=True, restart=True, wd=wd, use_saved_data=True)
v = connect(self._getConnStr(), wait_ready=True)
# This fn actually rate limits itself to every 2s.
# Just retry with persistence to get our first param stream.
v._master.param_fetch_all()
v.wait_ready()
actualValue = v._params_map[key]
assert actualValue == value
v.close()
def close(self):
self._sitl.stop()
usedINums.remove(self.iNum)
lazy decorator is from this library:
https://docs.python.org/2/tutorial/classes.html#generator-expressions
It would help to see how your class looks, but if it has methods from multiprocessing you may have issues just pickling it by default. Multiprocessing objects can use locks as well, and these are (obviously) unpickle-able.
You can customize pickling with the __getstate__ method, or __reduce__ (documented in the same place).
I'm probably missing something obvious, but I've been trying to solve this problem for about an hour, without any success. Probably going to feel really stupid when the solution is found. Here's the error I'm getting:
File "xpc_connection.py", line 77
def remoteObjectProxy():
^
IndentationError: unexpected indent
If I delete that portion of code, I get an indent error for the next line. There are some super strange problems going on with my indenting ...
Here's my code (yes, I know it's rather incomplete, and may have a few issues):
from collections import namedtuple;
import socket;
import sys;
from recvTimeout import recv_timeout
from recvTimeout import recv_end
from recvTimeout import sendAllWithEnd
# Named tuple that defines struct-like structure.
# field1 - body length, field2 - headerChecksum, field3 - checksum
XPCMessageHeader = namedtuple("XPCMessageHeader", "field1 field2 field3");
class XPCConnection(object):
"""An class that represents a connection made between processes using XPC.
Attributes:
"""
def __init__(self, serviceName):
self._serviceName = serviceName;
self._exportedObject = None; # This process's "representation" of itself.
self._remoteObjectProxy = None; # This process's "representation" of the remote process.
self._exportedObjectInterface = None; # Methods allowed to be received by exported object on this connection.
self._remoteObjectInterface = None; # Methods allowed to be received by object that has been "imported"
# to this connection.
self._connectionSocket = None # Domain socket that is endpoint of connection between processes.
def connect():
# Create a UDS socket
_connectionSocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Change this to port where remote process is listening.
print >>sys.stderr, 'connecting to %s' % _serviceName
try:
_connectionSocket.connect(_serviceName)
except socket.error, msg:
print >>sys.stderr, msg
sys.exit(1)
print >>sys.stderr, 'Attempting to connect.'
try:
# Send data
sendAllWithEnd(_connectionSocket,'Connected Successfully.')
data = recv_end(_connectionSocket);
print >>sys.stderr, 'received "%s"' % data;
except socket.error:
print >>sys.stderr, 'Connection Failed.';
def disconnect():
print >>sys.stderr, 'closing socket';
_connectionSocket.close();
def serviceName():
return serviceName;
#TODO
'''
def readMessage():
def readMessage():
def resume():
def invalidate():
'''
def remoteObjectProxy():
return _remoteObjectProxy;
#classmethod
def setRemoteObjectProxy(cls):
_remoteObjectProxy = CreateWithConnection(cls); # Create a remoteObjectProxy object with connection
# field that is this connection object.
def exportedObject():
return exportedObject;
def setExportedObject(exportedObject):
_exportedObject = exportedObject;
'''
# PRIVATE Helper Methods
# invocation of type XPCInvocation, completionHandler of type XPCInvocationCompletionHandler
# return type void
def _invokeOnRemoteObject(invocation, completionHandler):
# invocation of type XPCInvocation
# return type XPCValue
def _invokeOnExportedObject(invocation):
# May be unnecessary for now.
# fd of type int (represents a file descriptor)
# return type bool (indicates success?)
def _setFileDescriptor(int fd):
# data of type DataRef
# return type void
def _write(data):
# Probably not necessary
# estimatedBytesToRead of type int
# return type void
def _readDataOnReadQueue(estimatedBytesToRead):
# Likely necessary
# bytes of type string, length of type int
# return type void
def _processDataOnReadQueue(bytes, length):
# Likely unecessary
# data of type DataRef
# return type void
def _writeDataOnWriteQueue(data):
# error of type ErrorRef
# return type void
def _terminateWithErrorSync(error):
# error of type Error Ref
# return type void
def _terminateWithErrorOnUserQueue(error):
# return type bool. Returns true if connected, false otherwise
def _isConnected():
# delayInSecond of type int. Not sure if you can pass in an argument like this.
# return type void
def _connectWithExponentialBackoff(delayInSeconds = 0.0625):
# return type bool. Returns true iff connected successfully
def _attemptToConnect():
# Likely unecessary
# return type void
def _flushRequestQueue():
# closes connection
# return type void
def _disconnect():
'''
#TODO: Invocation handler equivalent.
# "This" process's representation of the other process.
class XPCRemoteObjectProxy(object):
def __init__(self, connection):
# Reference to the connection Remote Object is a part of. Necessary so that when
# you invoke a method and get stuff back, reomte object proxy knows where to send stuff back to.
self._connection = connection;
def invoke(invocation):
_connection.invokeOneRemoteObject(invocation); # TODO: invokeOneRemoteObject
# Used to represent "this" process.
class XPCExportedObject(object):
def __init__(self):
self._invocationHandlersByMethodSignature = {}; # Invocation handlers stored in dictionary. Keyed by method signatures.
# invocation is XPCInfocation object, returnValue XPCValue object
def invoke(invocation, returnValue):
try:
# We directly modify returnValue here. Unsure if this acutally works.
returnValue = _invocationHandlersByMethodSignature[methodSignature()];
return True;
except KeyError:
return False;
# Handler is of type XPCInvocationHandler and methodName is of type string.
# Come back to this
def registerInvocationHandlerForMethodSignature(handler, methodName):
return True
# Used to call a method across an XPC connection.
class XPCInvocation(object):
def __init__(self):
self._methodSignature = ""; # Signature of method to be called.
self._arguments = []; # List of arguments for the called method. Elements are XPCValue objects.
# TODO: This is definitely incorrect.
# Make this a classmethod?
def createFromSerializedRepresentation(serializedRepresentation):
invocation = self.__class__();
invocation.setMethodSignature(serializedRepresentation.methodsignature());
for serializedValue in serializedRepresentation.values():
invocation._arguments.append(FromSerializedRepresentation(serializedValue));
# Note: FromSerializedRepresentation function defined in XPCValue class.
# TODO: XPCValue Class
return invocation;
def getMethodSignature():
return _methodSignature;
def setMethodSignature(methodSignature):
_methodSignature = methodSignature;
def getArguments():
return _arguments
# Takes in an XPCValue as an argument.
def appendArgument(value):
_arguments.append(value);
# TODO: This is definitely incorrect.
# NOTE: XPCInvocationMessage has yet to be written. It is provided by protobuf.
def serializedRepresentation():
message = XPCInvocationMessage();
message.set_methodsignature(_methodSignature);
for value in _arguments:
message.add_values().CopyFrom(value.serializedRepresentation());
return message
You're using multi-line strings to substitute for multi-line comments. They are not comments, however, and when they're dedented all the way out like that, then it terminates the class scope and you can't get back into it.
Quick fix, indent the opening ''' to match the class scope.
I'd like to use the python module timeit to time some functions in my QGIS plugin.
Here, I've called the time it function within a function that I call at the end of the last function. It seems, though, that the plugin is taking even longer to run than usual and I am wondering if i'm calling the timer in the wrong place. Is there a better way to set this up?
class myPluginName:
def firstFunction(self):
...
self.secondFunction()
def secondFunction(self):
...
self.timeThings()
def run(self):
self.firstFunction()
def timeThings(self):
QMessageBox.information(None, 'First Function', 'Time : %s' % timeit.timeit(self.firstFunction,number=1)
QMessageBox.information(None, 'Second Function', 'Time : %s' % timeit.timeit(self.secondFunction,number=1)
UPDATE: After following some advice, i've tried to implement the wrapper in the following way. I get however, a TypeError: firstFunction() takes exactly 1 argument (2 given) on ret = func(**args, **kwargs)
def time_func(func):
try:
name = func.__name__
except:
name = func.f__name
def tf_wrapper(*args, **kwargs):
t = time.time()
ret = func(*args, **kwargs)
QMessageLog.logMessage("{}: {}".format(name, time.time() - t))
return ret
return tf_wrapper
class myPlugin:
def initGui(self):
QObject.connect(self.dlg.ui.comboBox,SIGNAL("currentIndexChanged(int)"), self.firstFunction)
#time_func
def firstFunc(self):
registry = QgsMapLayerRegistry.instance()
firstID = str(self.dlg.ui.firstCombo.itemData(self.dlg.ui.firstCombo.currentIndex()))
secondID = str(self.dlg.ui.secondCombo.itemData(self.dlg.ui.secondCombo.currentIndex()))
self.firstLayer = registry.mapLayer(firstID)
self.secondLayer = registry.mapLayer(secondID)
#time_func
def secondFunc(self):
...
self.thirdFunc()
def thirdFunct(self):
...
def run(self):
self.dlg.ui.firstCombo.clear()
self.dlg.ui.secondCombo.clear()
for layer in self.iface.legendInterface().layers():
if layer.type() == QgsMapLayer.VectorLayer:
self.dlg.ui.firstCombo.addItem(layer.name(), layer.id())
self.dlg.ui.secondCombo.addItem(layer.name(), layer.id())
result = self.dlg.exec_()
if result == 1:
self.secondFunction()
OK, I don't know your exact situation, but I'd set it up though decorators:
import time
def time_func(func):
try:
name = func.__name__
except:
name = func.f_name
def tf_wrapper(*args, **kwargs):
t = time.time()
ret = func(*args, **kwargs)
print("{}: {}".format(name, time.time() - t)) # Or use QMessageBox
return ret
return tf_wrapper
class myPluginName:
#time_func
def firstFunction(self):
pass
#time_func
def secondFunction(self):
pass
def run(self):
self.firstFunction()
myPluginName().firstFunction()
With this code, any function wrapped in time_func will have the time taken to execute the function printed when it returns, along with its name. E.g. running it will print:
firstFunction: 1.430511474609375e-06
For your TypeError, you need to change;
def firstFunction(self):
pass
To:
def firstFunction(self, index):
pass
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.
I'm trying to make a class that is borg-like. I'd like one particular property to be shared by all the instances, but other properites I would like to be unique to the instance. Here is what I have so far:
class SharedFacility:
_facility = None
def __init__(self):
entries = {'facility': self._facility}
self.__dict__.update(entries)
def _getfacility(self):
return self._facility
def _setfacility(self, value):
self._facility = value
facility = property(_getfacility, _setfacility)
class Warning(SharedFacility):
def __init__(self, warnlevel, warntext):
SharedFacility.__init__(self)
print "Warning.__init__()"
self.warntext = warntext
self.warnlevel = warnlevel
def __call__(self):
self.facility(self.warnlevel, self.warntext)
def functionOne(a,b):
print 'functionOne: a=%s, b=%s' % (a,b)
def functionTwo(a,b):
print 'functionTwo: a=%s, b=%s' % (a,b)
####################################################
w1 = Warning(1, 'something bad happened')
w1.facility = functionOne
w2 = Warning(5, 'something else bad happened')
import pdb; pdb.set_trace()
if w1.facility is w2.facility:
print "They match!"
w1() # functionOne: a=1, b='something bad happened'
w2() # functionOne: a=5, b='something else bad happened'
w2.facility = functionTwo
if w1.facility is w2.facility:
print "They match!"
w1() # functionTwo: a=1, b='something bad happened'
w2() # functionTwo: a=5, b='something else bad happened'
The above code does not work. I'd like w1.facility and w2.facility to be a reference to the same object, but w1.warntext and w2.warntext two be two different values. I'm working with python 2.4.3 (no sense in mentioning I upgrade because I can't).
Solution:
class Warning(object):
_facility = None
def __init__(self, warnlevel, warntext):
print "Warning.__init__()"
self._warntext = warntext
self._warnlevel = warnlevel
def __call__(self):
Warning._facility(self._warnlevel, self._warntext)
def _getfacility(self):
return Warning._facility
def _setfacility(self, value):
Warning._facility = value
facility = property(_getfacility, _setfacility)
#staticmethod
def functionOne(a,b):
print 'functionOne: a=%s, b=%s' % (a,b)
#staticmethod
def functionTwo(a,b):
print 'functionTwo: a=%s, b=%s' % (a,b)
Here's what I would do:
class BorgLike:
_shared = 'default'
def __init__(self, unique):
self.unique = unique
#property
def shared(self):
return BorgLike._shared
#shared.setter
def shared(self, value):
BorgLike._shared = value
I hope you know how to use this example for your own purpose. I wasn't really sure what you wanted with your code, so I refrained from guessing and wrote a minimal example.