Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocesss: call an instance method

I am using Python 2.7. I want to create an instance of an object, and call a method within it in a separate process. Something like this:

import subprocesss
class A
   def doAwork(self, text):
      print text

class B
   def doBWork
      aInst = A()
      subprocess(A.dowork("called from doBwork"))

Can this be done, or, do I need to turn around and call python as a subprocesss?

Edit: I can not use threads for this. The method called in aInst in reality loads a non-thread safe dll.

Thanks

like image 695
Doo Dah Avatar asked Feb 15 '26 09:02

Doo Dah


1 Answers

You have to use the multiprocessing module instead of subprocess

Simple example copied from documentation link above:

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

With your example it would look like this:

from multiprocessing import Process

class A:
   def doAwork(self, text):
      print text

class B:
   def doBweork(self):
      aInst = A()
      p = Process(target=aInst.doAwork("called from doBWork")
      p.start()
      p.join()
like image 167
TobiMarg Avatar answered Feb 17 '26 21:02

TobiMarg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!