Pythonスクリプトの実行中のインスタンスすべてに更新イベントを通知する必要があり、できるだけシンプルにコードを保持したいと考えています。私は、実行中のプロセス間での通信経験はありません。これまで、私は各インスタンスが読み書きする構成ファイルを読み書きしていました。同じPythonスクリプトの複数の実行インスタンスに更新イベントを通知する必要があります
私はこの問題を解決する方法について私の頭を包むために書いた(シンプルなテンプレートの一種)いくつかの擬似コードを示します。空白を埋めるのを手伝ってください。覚えておいて、私はソケット、スレッドなどの経験がありません。
import process # imaginary module
class AppA():
def __init__(self):
# Every instance that opens will need to attach
# itself to the "Instance Manager". If no manager
# exists, then we need to spawn it. Only one manager
# will ever exist no matter how many instances are
# running.
try:
hm = process.get_handle(AppA_InstanceManager)
except NoSuchProgError:
hm.spawn_instance(AppA_InstanceManager)
finally:
hm.register(self)
self.instance_manager = hm
def state_update(self):
# This method won't exist in the real code, however,
# it emulates internal state changes for the sake of
# explaination.
#
# When any internal state changes happen, we will then
# propagate the changes outward by calling the
# appropriate method of "self.instance_manager".
self.instance_manager.propagate_state()
def cb_state_update(self):
# Called from the "Instance Manager" only!
#
# This may be as simple as reading a known
# config file. Or could simply pass data
# to this method.
class AppA_InstanceManager():
def __init__(self):
self.instances = []
def register_instance(self, instance):
self.instances.append(instance)
def unregister_instance(self, instance):
# nieve example for now.
self.instances.remove(instance)
def propagate_state(self):
for instance in self.instances:
instance.cb_state_update(data)
if __name__ == '__main__':
app = AppA()
何か提案がありますか?
あなたが "インスタンス"と言うとき、シェルスクリプトなどから複数の同時インタプリタを起動しているのですか、あるいは単一のPythonインタプリタインスタンスから複数のインスタンスを生成していますか?どのようなアプローチが有効になるかという点で違いがあります。 –
うーん、正確にはわからない(私の無知に対する謝罪)。私は最初のスクリプトアプリケーションの各インスタンスのための "python.exe"(タスクマネージャで)の1つのインスタンスを見ることができるので、最初に信じています。それは役に立ちますか? – Joe
はい、そうです。私はかなりあなたのシステムを大幅に再構築することなく、マルチスレッド/マルチプロセスを使用することを妨げることは間違いないと確信しています。プロセス間のデータフローを制御するには、DBやファイルなどの外部ソースを使用する必要があると思います。しかし、もし柔軟に再構築することができれば、mutliprocess/mutlithreadが望ましいかもしれません。 –