Creating a signal with parameters in PyQt - pyqt4

I am using the following example
class bar(QObject):
def mySlot(self,p):
print "This is my slot " + str(p)
class Foo(QObject):
trigger = pyqtSignal()
def my_connect_and_emit_trigger(self):
self.trigger.emit(12)
def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"
b = bar()
a = Foo()
a.trigger.connect(int,b.mySlot) <---how to fix this
a.connect_and_emit_trigger()
I am trying to attach the slot b.mySlotwhich takes one int parameter to a signal a.trigger my question is what am I doing wrong. I could not find any material that helps with parameters of signals.

this is correct:
class bar(QObject):
def mySlot(self,p):
print "This is my slot " + str(p)
class Foo(QObject):
trigger = pyqtSignal(int)
def my_connect_and_emit_trigger(self):
self.trigger.emit(12)
def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"
b = bar()
a = Foo()
a.trigger.connect(b.mySlot)
a.my_connect_and_emit_trigger()
Doc is here

Related

Python for loop calls a function that calls another function

I am using a for loop to iterate over a list of switches.
For each device in switch_list, I call function1.
Function1 then calls function2.
However, that's when the processing ends.
I need to get back to the for loop so that I can process switch2, switch3, etc...
Here is the output:
We are in main
We are in function1 and the device name is switch1
We are in function2 and the device name is switch1
Here is my code:
switch_list = ['switch1', 'switch2']
def main():
print('We are in main')
for device in switch_list:
main_action = function1(device)
return(device)
def function1(device):
print(f'We are in function1 and the device name is {device}')
function1_action = function2(device)
def function2(device):
print(f'We are in function2 and the device name is {device}')
if __name__ == '__main__':
main()
Any assistance would be greatly appreciated.
It's because the return() statement in your main function is inside the for loop. Your problem would be solved if you take it out of the for loop.
return() symbolizes the end of a function. So when your code sees the return statement, it exits main() and you get output for only the first device.
You can create a list of the devices since you are running a for loop and pass it on after it's completion.
Something like this:
def main():
main_output_list = []
print("We are in main")
for device in switches:
main_action = function1(device)
main_output_list.append(output of main)
return(main_output_list)
As suggested by Alexander, the return keyword exits the function, returning a provided value to the place where the method was called.
ex.
def give_10():
return 10
print("I am unreachable because I am after a return statement")
print(give_10()) # give_10() returns 10 which makes the statement
# as print(10). Which in turn processes the value and prints to stdout.

Dart: Store heavy object in an isolate and access its method from main isolate without reinstatiating it

is it possible in Dart to instantiate a class in an isolate, and then send message to this isolate to receive a return value from its methods (instead of spawning a new isolate and re instantiate the same class every time)? I have a class with a long initialization, and heavy methods. I want to initialize it once and then access its methods without compromising the performance of the main isolate.
Edit: I mistakenly answered this question thinking python rather than dart. snakes on the brain / snakes on a plane
I am not familiar with dart programming, but it would seem the concurrency model has a lot of similarities (isolated memory, message passing, etc..). I was able to find an example of 2 way message passing with a dart isolate. There's a little difference in how it gets set-up, and the streams are a bit simpler than python Queue's, but in general the idea is the same.
Basically:
Create a port to receive data from the isolate
Create the isolate passing it the port it will send data back on
Within the isolate, create the port it will listen on, and send the other end of it back to main (so main can send messages)
Determine and implement a simple messaging protocol for remote method call on an object contained within the isolate.
This is basically duplicating what a multiprocessing.Manager class does, however it can be helpful to have a simplified example of how it can work:
from multiprocessing import Process, Lock, Queue
from time import sleep
class HeavyObject:
def __init__(self, x):
self._x = x
sleep(5) #heavy init
def heavy_method(self, y):
sleep(.2) #medium weight method
return self._x + y
def HO_server(in_q, out_q):
ho = HeavyObject(5)
#msg format for remote method call: ("method_name", (arg1, arg2, ...), {"kwarg1": 1, "kwarg2": 2, ...})
#pass None to exit worker cleanly
for msg in iter(in_q.get, None): #get a remote call message from the queue
out_q.put(getattr(ho, msg[0])(*msg[1], **msg[2])) #call the method with the args, and put the result back on the queue
class RMC_helper: #remote method caller for convienience
def __init__(self, in_queue, out_queue, lock):
self.in_q = in_queue
self.out_q = out_queue
self.l = lock
self.method = None
def __call__(self, *args, **kwargs):
if self.method is None:
raise Exception("no method to call")
with self.l: #isolate access to queue so results don't pile up and get popped off in possibly wrong order
print("put to queue: ", (self.method, args, kwargs))
self.in_q.put((self.method, args, kwargs))
return self.out_q.get()
def __getattr__(self, name):
if not name.startswith("__"):
self.method = name
return self
else:
super().__getattr__(name)
def child_worker(remote):
print("child", remote.heavy_method(5)) #prints 10
sleep(3) #child works on something else
print("child", remote.heavy_method(2)) #prints 7
if __name__ == "__main__":
in_queue = Queue()
out_queue = Queue()
lock = Lock() #lock is used as to not confuse which reply goes to which request
remote = RMC_helper(in_queue, out_queue, lock)
Server = Process(target=HO_server, args=(in_queue, out_queue))
Server.start()
Worker = Process(target=child_worker, args=(remote, ))
Worker.start()
print("main", remote.heavy_method(3)) #this will *probably* start first due to startup time of child
Worker.join()
with lock:
in_queue.put(None)
Server.join()
print("done")

Python 3 : Getter is not returning the data it should be

I have a parent Class that has a setter that returns queryFiltre value and a getter that is supposed to pass the queryFiltre value to my child Class. queryFiltre Should return an SQL query like "SELECT * FROM Report WHERE GA_RPM > 0 and CAMPAIGN LIKE '%TT%'... ".
The print() in the setter returns a SQL query, but the print() of the getter when called in the child Class returns something like " <main.SimpleGrid object at 0x042AF2B0>".
What's wrong with my code? Please bear with me as I'm still learning and oop is still an abstract concept in my head.
I've added comments in the code so you can see what happens where:
class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
def __init__(self, parent, log):
gridlib.Grid.__init__(self, parent, -1)
########### DATABASE CONNECT
self.path =os.path.dirname(os.path.realpath(__file__))
self.dbfile = os.path.join(self.path , "report.db")
self.db_conn = sqlite3.connect(self.dbfile)
self.theCursor = self.db_conn.cursor()
########### SETTING FILE CONNECT
self.configFile = os.path.join(self.path , "config.ini")
self.config = configparser.ConfigParser()
self.config.read(self.configFile)
########### Calling th Getter and Setter
self.queryFiltre = self.setQueryFiltre(self)
self.getQueryFiltre()
########### Setter
def setQueryFiltre(self,queryFiltre):
if self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "true":
network = ""
elif self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "false":
network = " and CAMPAIGN LIKE '%TB%'"
elif self.config.get('Network', 'outbrain') == "true" and self.config.get('Network', 'tb') == "false":
network = " and CAMPAIGN LIKE '%OB%'"
else:
network = ""
queryFiltre = "SELECT * FROM Report WHERE GA_RPM > 0 " + network + " and STATUS = '1' ORDER BY CLICKS DESC"
########### The print below returns the right value of queryFiltre
print(queryFiltre)
return queryFiltre
########### Getter
def getQueryFiltre(queryFiltre):
queryFiltre = queryFiltre
return queryFiltre
class TestFrame(wx.Frame):
def __init__(self, parent, log):
wx.Frame.__init__(self, parent, 0, "Native Ads Reports V1.0", size=(1400,800))
self.grid = SimpleGrid(self, log)
########### Calling the Getter of the parent Class
self.queryFiltre = self.grid.getQueryFiltre()
########### DATABASE CONNECT
self.path =os.path.dirname(os.path.realpath(__file__))
self.dbfile = os.path.join(self.path , "report.db")
self.db_conn = sqlite3.connect(self.dbfile)
self.theCursor = self.db_conn.cursor()
########### The print below returns a bad value, something like : <__main__.SimpleGrid object at 0x042AF2B0>
print(self.queryFiltre)
You'll notice also that I've added the script to define the path and to connect to the db in both classes, is there a way to do it only once in the first Class?
Thank you,
Your getQueryFiltre() in SimpleGrid has the wrong indentation, and is missing the first argument self. The way you've written it, it is a function within the scope of your setQueryFiltre(), and it isn't called from anywhere.
It should be indented to the same level as setQueryFiltre, and have a first argument self.
By the way, you shouldn't be using getters. It's not pythonic, as explained here: https://stackoverflow.com/a/36943813/11451509

Python - Implementing stop method in threading.Thread

I'm using threads in my project I want to subclass threading.Thread and implement the stop method there, so I can subclass this class. look at this -
class MyThread(threading.Thread):
__metaclass__ = ABCMeta
def run(self):
try:
self.code()
except MyThread.__StopThreadException:
print "thread stopped."
#abstractmethod
def code(self):
pass
def stop(self):
tid = self.get_id()
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
ctypes.py_object(MyThread.__StopThreadException))
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
class __StopThreadException(Exception):
"""The exception I raise to stop the sniffing"""
pass
def get_id(self):
for tid, tobj in threading._active.items():
if tobj is self:
return tid
class SniffThread(MyThread):
def code(self):
sniff(prn=self.prn)
def prn(self, pkt):
print "got packet"
t = SniffThread()
t.start()
time.sleep(10)
t.stop()
It doesn't work because the StopThreadException is raised in the main thread, and I need to find a way to raise it in the SniffThread. Do you have better way to implement the stop method? I need to do it because I work with blocking functions and I need a way to stop the Thread. I know I can use the lfilter of the sniff function and keep a flag but I don't want to do this. I don't want to do it because it will only work with scapy and I want to make an abstract class that can be inherited with a stop method that will work for any thread, the solution needs to be in the MyThread class.
Edit: I looked here and changed my code.

Call Function inside of another class that is threaded

I am writing a gui application in python. In one instance of the GUI I want to call a method inside of my thread class, but I don't want to call the initial run() method.
Here is an example of my Threaded class:
class SomeThread(Thread):
def __init__(self,queue):
self.queue = queue
Thread.__init__(self)
def SomeMethod():
print "success"
def run(self):
apple = "eat a apple"
self.queue.put(apple) # pass var into queue
I attempt to call the SomeMethod here
class SomeGUIClass(wx.Frame):
def MethodA(self,event):
SomeThread.SomeMethod()
But I get an error that states "type object 'SomeThread' has no attribute 'SomeMethod'. How can I call this SomeMethod function directly without executing the run(self) method?
I believe the text editor had some trouble with the tabs/spacing of certain elements. I got it to work after fixing the indentation by calling:
self.queue = Queue.Queue()
SomeThread(self.queue).SomeMethod()

Resources