8

I'm use a library which provides a python interface to an external program. This allows me to create:

foo = Foo()

The code above starts a new instance of the Foo program that I can control from within python.

I have a python scripts which needs to be invoked multiple times and depending on external parameters, tell a single instance of the external Foo program to do different things. Obvious I can't do

foo = Foo() everytime,

since that creates a new instance of Foo every time my script runs.

What I want to do is to create foo= Foo() once, and have multiple invocations share the same instance. Currently I'm thinkibng of just creating it once, serialize it, and have my scripts deserialize it. Does this approach work? Is there a better alternative?

Thanks!!

Trufa
  • 39,971
  • 43
  • 126
  • 190
wk1989
  • 611
  • 1
  • 8
  • 19

3 Answers3

3

This can be done if you follow an approach similar to that given in this answer. Or you can use Pyro, which is compared to multiprocessing in this answer.

Community
  • 1
  • 1
Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
0

You might be able to use pickle. Here's a simple example:

import os, pickle

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

# use previous pickled instance if found
if os.path.exists('foo.pickle'):
    with open('foo.pickle') as f:
        foo = pickle.load(f)
else:
    foo = Foo(42)

# print current foo.bar
print foo.bar

# change foo.bar and pickle
foo.bar = raw_input('new bar: ')
with open('foo.pickle', 'w') as f:
    pickle.dump(foo, f)
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
  • I tried doing that actually, I got a message saying "Can't pickle 'lock' object: ". I'm looking into it now. – wk1989 Jun 26 '11 at 02:47
  • Yeah, it has limitations which you may/may not be able to work around to do what you want: http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled – Zach Kelling Jun 26 '11 at 02:59
  • 2
    if you're using a lock, you probably need to take another path like sockets or pipes to provide locked access to your class – lunixbochs Jun 26 '11 at 03:39
0

You can change the design so that Foo() just connects you to an existing process, and then you create a new function, call it startFoo() that you previously call once (or if Foo() fails). Even better would be to make the program that Foo() connects to a service that you connect to over a socket. You might also want to just switch to the multiprocessing module.

Keith
  • 42,110
  • 11
  • 57
  • 76
  • Yeah I think that's what i'll have to do seeing as I can't serialize the the Foo object easily. – wk1989 Jun 26 '11 at 16:31