Python 3.5 code - classes not correct defined - python

I have a simple code problem and do not know what I do wrong. The import part is OK, when I get as an error message is that, I guess I make a mistake with the classes.
status_listener = SessionStatusListener()
TypeError: interface takes exactly one argument
So the code is:
import clr
clr.AddReference ("fxcore2")
from fxcore2 import O2GTransport, IO2GSessionStatus
class SessionStatusListener(IO2GSessionStatus):
def __init__(self):
IO2GSessionStatus.__init__(self)
self.connected = False
def onLoginFailed(self, error):
print ("*** LOGIN FAILED: %s" % error)
def onSessionStatusChanged(self, status):
print ("NEW STATUS: %s" % status)
if status == O2GSessionStatusCode.Connected:
self.connected = True
The main Application starts here
if __name__ == "__main__":
session = O2GTransport.createSession()
status_listener = SessionStatusListener()
Any advice is appreciated.

Pass an argument to SessionStatusListener, like it's telling you to. I would imagine that you need to change the __init__ body to something like
super().__init__(self)
instead of
IO2GSessionStatus.__init__(self)

I believe it is saying that
status_listener = SessionStatusListener()
Needs one argument, like this:
status_listener = SessionStatusListener(1)
I'm not sure exactly what types of data it's expecting, but you need to pass in an argument.

Related

How to store Observer on_completed result

I am relatively new to Rx and RxPy - there is one fundamental thing that I am trying to do which is access a value that I store at the end of an Observer on_completed. I have a feeling I am either missing something very obvious, or I am perhaps bending the Observable concept into something that it's not meant to be. Either way, hoping I can get some guidance on this.
I've looked over the documentation at things like materialize but they don't quite seem to match up. Have also looked into Do and Disposable but can't find many examples that are close to what I need.
import rx
from rx import operators as ops
from rx.core import Observer
if __name__ == "__main__":
class PipelineObserver(Observer):
def __init__(self):
self.status = None
def on_next(self, payload):
print(payload)
def on_error(self, err):
print(err)
def on_completed(self):
self.status = "Done"
return self.status
## This returns a disposable, not the actual value I want. Which in this case is self.status
output = rx.from_([1, 2]).subscribe(
PipelineObserver()
)
print(output) ## Hoping for "Done" which is stored in self.status, not disposable class
Is there anyway to access a value a value from the on_completed method? Short of saving something as a global variable (which seems like a bad idea to me) I'm not sure it's possible? Basically whatever it output by on_completed or something similar. Maybe Do or Finally?
Ended up figuring it out, posting here in case anyone else runs into this. Due to this operation I am looking for being one that has to run after an observable is completed, it has to be a blocking operation. The run() function is used for this.
import rx
from rx import operators as ops
from rx.core import Observer
if __name__ == "__main__":
class PipelineObserver(Observer):
def __init__(self):
self.status = None
def on_next(self, payload):
print(payload)
def on_error(self, err):
print(err)
def on_completed(self):
self.status = "Done"
# First, seperate out the observer and observable:
my_list = rx.from_([1, 2])
my_list.subscribe(
PipelineObserver()
)
# Say I want to return an integer of the count of items, I can use this:
output = my_list.pipe(
ops.count()
).run()
print(output)
# Notice the run command at the end of the chain.
# Output: 2
There might be other/better ways of doing this but this will work for now!

setUp section in unit-tests seems to be ignored

class MyTests(unittest.TestCase):
def SetUp(self):
""" Setting up expected default values """
self.test = RandomTest()
def testReturnsArrayWithTuples(self):
result = self.test.next() # Error
self.assert_(len(result), 5)
if __name__ == "__main__":
unittest.main()
I have a basic test, but it fails with this error message:
AttributeError: 'MyTests' object has no attribute 'test'
Eclipse intellisense is showing me self.test though. What am I missing please?
Ok, its quite embarrassing, as it was just a typo. :)
def SetUp(self): has to be lowercase def setUp(self): in order to be found and executed.
I hope it prevents someone else chasing ghosts like I did.

Invoking a program in python

Is there a way for a program to invoke another program in python?
Let me explain my problem:
I am building an application (program 1) , I am also writing a debugger to catch exceptions (program 2) in program 1 { a typical try : except: } block of code . Now I want to release program 2 so that for any application like prog 1 , prog 2 can handle exceptions ( making my work easier) . I just want prog 1 to use a simple piece of code like:
import prog2
My confusion stems from the fact as how can I do something like this , how can I invoke prog 2 in prog 1, ie it should function as all the code in prog 1 should run in the {try: (prog 1) , except:} prog 2 try block.
Any pointers on how I can do this or a direction to start would we very much appreciated.
Note: I am using python 2.7 and IDLE as my developer tool.
tried execfile() yet? Read up on it on how to execute another script from your script.
I think you need to think about classes instead of scripts.
What about this?
class MyClass:
def __init__(self, t):
self.property = t
self.catchBugs()
def catchBugs(self):
message = self.property
try:
assert message == 'hello'
except AssertionError:
print "String doesn't match expected input"
a = MyClass('hell') # prints 'String doesn't match expected input'
UPDATE
I guess you have something like this in your directory:
program1.py (main program)
program2.py (debugger)
__init__.py
Program1
from program2 import BugCatcher
class MainClass:
def __init__(self, a):
self.property = a
obj = MainClass('hell')
bugs = BugCatcher(obj)
Program2
class BugCatcher(object):
def __init__(self, obj):
self.obj = obj
self.catchBugs()
def catchBugs(self):
obj = self.obj
try:
assert obj.property == 'hello'
except AssertionError:
print 'Error'
Here we are passing the whole object of your program1 to the BugCatcher object of program2. Then we access some property of that object to verify that it's what we expect.

Proper naming scope for custom error handlers in Python

I'm trying to write an error handling class for my application. Is it necessary to include the full path to the error handler every time? Below is my code.
appname/appname/model/error.py
class UserError(Exception):
""" User errors
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
My class function:
from error import UserError
def doSomething(
""" Some function
"""
if (value == 2):
pass
else:
raise UserError('Value is not 2')
That is called from my application as follows:
from error import UserError
try:
print names['first']
except appname.model.error.UserError as e:
print e
When raised:
>> appname.model.error.UserError: 'No file specified'
Do I have to refer to this as "appname.model.error.UserError" all the time? Or is there a way to just refer to this error as UserError or even error.UserError? Where to I adjust the scope of this? Seems like not a good idea in case I change the directory structure (or even name) of my application, no?
You could do this:
from appname.model.error import UserError

Problem with import in Python

[Closing NOTE]
Thank you everyone that trying to help me.
I've found the problem and it have nothing to do with python understanding of mine (which is little). :p
The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.
Thanks anyway.
[Original Question]
I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem
First I have python files like this:
src/
main.py
SomeUtils.py
In "SomeUtils.py, I have a few functions and one class:
...
def funct1 ...
def funct2 ...
class MyClass1:
__init__(self):
self. ....
...
Then in "main.py", I use the function and class:
from SomeUtils import *;
def main():
funct1(); # Use funct1 without problem;
aMyObj1 = MyClass1(); # Use MyClass1 with error
if (__name__ == "__main__"):
main();
The problem is that the functions are used without any problem what so ever but I cannot use the class.
The error is:
NameError: global name 'MyClass1' is not defined
What is the problem here? and What can I do?
EDIT: Thanks for answers for I still have problem. :(
When I change the import statements to:
from SomeUtils import funct1
from SomeUtils import MyClass1
I have this error
ImportError: cannot import name MyClass1
EDIT 2:----------------------------------------------------------
Thanks you guys.
I think, it may be better to post the actual code, so here it is:
NOTE: I am aware about ";" and "(...)" but I like it this way.
Here is the dir structure.
DIRS http://dl.getdropbox.com/u/1961549/images/Python_import_prolem_dir_.png
as you see, I just add an empty init.py but it seems to make no different.
Here is main.py:
from XWinInfos import GetCurrentWindowTitle;
from XWinInfos import XWinInfo;
def main():
print GetCurrentWindowTitle();
aXWinInfo = XWinInfo();
if (__name__ == "__main__"):
main();
Here is XWinInfos.py:
from subprocess import Popen;
from subprocess import PIPE;
from RegExUtils import GetTail_ofLine_withPrefix;
def GetCurrentWindowID():
aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0];
aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp);
return aLine;
def GetCurrentWindowTitle():
aWinID = GetCurrentWindowID();
aWinTitle = GetWindowTitle(aWinID);
return aWinTitle;
def GetWindowTitle(pWinID):
if (aWinID == None): return None
aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0];
aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList);
return aWinTitle;
class XWinInfo:
def __init__(self):
aWinID = GetCurrentWindowID();
self.WinID = pWinID;
self.Title = GetWindowTitle(pWinID);
The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.
If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".
If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".
Please helps.
Thanks in advance.
Hmm... there's several typos in your example, so I wonder if your actual code has some typos as well. Here's the complete source from a quick test that does work fine without import errors.
SomeUtils.py:
def funct1():
print('Function 1')
def funct2():
print('Function 2')
class MyClass1(object):
def __init__(self):
print('MyClass')
main.py:
from SomeUtils import *
def main():
funct1()
aObj = MyClass1()
if (__name__ == "__main__"):
main()
[EDIT Based on OP additional info]
I still can't recreate the same error, but the code you posted won't initially work for at least a couple of errors in the XWinInfox.py init method:
self.WinID = pWinID #change to 'aWinID' since pWinID is not defined
self.Title = GetWindowTitle(pWinID) #change to 'aWinID'since pWinID is not defined
so a corrected version would read:
self.WinID = aWinID
self.Title = GetWindowTitle(aWinID)
Also, you have a typo in your init file name, there should be two underscores before AND after the 'init' word. Right now you have '__init_.py' and it should be '__init__.py', however this shouldn't keep your code from working.
Because I don't have the RegExUtils.py code, I just stubbed out the methods that rely on that file. With the stubbed methods and correcting the aforementioned typos, the code you post now works.
why are you importing from XWinInfos? you should be importing from SomeUtils. Not to mention that *-style imports are discouraged.
Edit: your error
ImportError: cannot import name MyClass1
basically tells you that there is no MyClass1 defined in the SomeUtils. It could be because you have another SomeUtils.py file somewhere on the system path and it being imported instead. If that file doesn't have MyClass1, you'd get this error.
Again: it's irrelevant whether you class MyClass1 exist. What might be the case is that you have another XWinInfos.p(y|o|w) somewhere on your system and it's being imported. Otherwise: norepro.
You may want to rewrite main.py as follows:
import SomeUtils as util
def main():
util.funct1() # Use funct1 without problem;
aMyObj1 = util.MyClass1() # Use MyClass1 with error
if __name__ == "__main__":
main()
A few quick notes:
There is no need for semicolons in
Python unless you have more than one
statement on a line
There is no need
to wrap conditional tests in
parentheses except for grouping
from
module import * is discouraged as it
pollutes the global namespace
I suppose you mean
from SomeUtils import *
however, that does not trigger the error for me. This works fine for me:
SomeUtils.py
def funct1():
print 4
class MyClass1:
def __init__(self):
print 8
main.py
from SomeUtils import *
def main():
funct1() # Use funct1 without problem;
aMyObj1 = MyClass1() # Use MyClass1 without error
if (__name__ == "__main__"):
main()
Your question is naturally linked to a lot of SO older one.
See, just for reference, SO1342128 and SO1057843

Categories

Resources