Python:如何在脚本的多次调用之间共享对象实例
我正在使用一个为外部程序提供 python 接口的库。这允许我创建:
foo = Foo()
上面的代码启动了 Foo 程序的一个新实例,我可以在 python 中控制它。
我有一个 python 脚本,需要多次调用,并根据外部参数告诉外部 Foo 程序的单个实例执行不同的操作。显然我不能
每次都执行 foo = Foo()
,
因为每次我的脚本运行时都会创建一个新的 Foo 实例。
我想要做的是创建 foo= Foo() 一次,并让多个调用共享同一个实例。目前我正在考虑只创建一次,序列化它,然后让我的脚本反序列化它。这种方法有效吗?有更好的选择吗?
谢谢!!
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!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您遵循类似于此答案。或者您可以使用 Pyro,它与 这个答案。
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.
您也许可以使用 pickle。这是一个简单的例子:
You might be able to use pickle. Here's a simple example:
您可以更改设计,以便
Foo()
仅将您连接到现有进程,然后创建一个新函数,将其命名为您之前调用过一次的startFoo()
(或者如果Foo()
失败)。更好的是让 Foo() 连接到您通过套接字连接的服务的程序。您可能还想切换到多处理模块。You can change the design so that
Foo()
just connects you to an existing process, and then you create a new function, call itstartFoo()
that you previously call once (or ifFoo()
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.