Question

This question might be unclear - if so, that probably because I'm not entirely shure how to ask the question - but here goes:

I have a Python class from which I would like to call a function.

The class does not have access to the data that the function should operate on - basically, I would like the class to send a message to another process, that calls the function. Something like:

from multiprocessing import Process

class Foo():
   def bar(phonenumber):
      do_something()
      send_message(phonenumber)

def daemon(data, phonenumber):
   while nothing_receivied(phonenumber):
      do_nothin()
      also_do_not_consume_too_much_CPU()
   if message_received(phonenumber):
      function(data)

p = Process(target=daemon, args=(data, phonenumber))
p.start()
p.join()

calling Foo.bar(phonenumber) should then have the extra effect that function is performed on data - how is this achievable?

Cheers!

Was it helpful?

Solution

If you specifically are trying to use the multiprocessing module, you should probably take a look into using a Queue/Pipe. http://docs.python.org/library/multiprocessing.html#pipes-and-queues

The part of your daemon code where you want to sit and do nothing while not consuming too much CPU is the point where it would try and get an item from the queue, or poll the pipe for data and block until something is ready. The other side of the queue or pipe would simply put data into the queue which fills the role of your send_message concept.

If you want a more robust asynchronous solution, you should also check out the Twisted libraries: http://twistedmatrix.com/trac/

This would allow you to define a service at a higher level that has an event loop with handlers to process incoming connections.

And lastly, if you just wanted a simple solution all in the same script and not anything network-based, you could easily just use the threading module: http://docs.python.org/library/threading.html . And use Queue.Queue for the daemon to block on with a get(), and send_message() doing a put()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top