0

物理IOを監視して操作するPythonプロセスがいくつかあります。たとえば、電流が高すぎる場合はモーターをシャットダウンします。彼らはなぜ彼らが何かをしたのかをお互いに知らせる必要があるので、共有ファイルは簡単な解決策かもしれないと思いました。さまざまなプロセスがこのファイルに書き込むことができ、他のプロセスはいつ書き込まれたかを知る必要があります。私はすでに静的構成ファイルにConfigObjを使用しているので、動的ファイルを試してみようと思いました。書き込みはそれほど頻繁には発生しないはずです。おそらく1秒に1回程度で、通常はそれよりもはるかに遅くなります。私はうまくいくように見えるこの例を思いついた。

import copy
import os.path
import threading
import time
from configobj import ConfigObj

class config_watcher(threading.Thread):
    def __init__(self,watched_items):
        self.watched_items = watched_items
        self.config = self.watched_items['config'] 
        super(config_watcher,self).__init__()
    def run(self):
        self.reload_config()
        while 1:
            # First look for external changes
            if self.watched_items['mtime'] <> os.path.getmtime(self.config.filename):
                print "external chage detected"
                self.reload_config()
            # Now look for external changes
            if self.watched_items['config'] <> self.watched_items['copy']: 
                print "internal chage detected"
                self.save_config()
            time.sleep(.1)
    def reload_config(self):
        try:
            self.config.reload()
        except Exception:
            pass
        self.watched_items['mtime'] = os.path.getmtime(self.config.filename)
        self.watched_items['copy'] = copy.deepcopy(self.config)
    def save_config(self):
        self.config.write()
        self.reload_config()

if __name__ == '__main__':
    from random import randint
    config_file = 'test.txt'
    openfile = open(config_file, 'w')
    openfile.write('x = 0 # comment\r\n')
    openfile.close()
    config = ConfigObj(config_file)
    watched_config = {'config':config} #Dictionary to pass to thread
    config_watcher = config_watcher(watched_config) #Start thread
    config_watcher.setDaemon(True) # and make it a daemon so we can exit on ctrl-c
    config_watcher.start()
    time.sleep(.1) # Let the daemon get going
    while 1:
        newval = randint(0,9)
        print "is:{0} was:{1}, altering dictionary".format(newval,config['x'])
        config['x'] = newval
        time.sleep(1)
        openfile = open(config.filename, 'w')
        openfile.write('x = {0} # external write\r\n'.format(randint(10,19)))
        openfile.close()
        time.sleep(1)
        print "is {1} was:{0}".format(newval,config['x'])
        time.sleep(1)

私の質問は、これを行うためのより良い/より簡単な/よりクリーンな方法があるかどうかです。

4

2 に答える 2

2

同じファイルを監視および更新しようとする複数のプロセスがある場合、アプローチは競合状態に対して脆弱です。

私はこれにSQLiteを使用する傾向があり、メッセージを記録するためにタイムスタンプ付きの「ログ」テーブルを作成します。「モニター」スレッドは、最大タイムスタンプまたは整数キー値をチェックするだけです。これはやり過ぎだと言う人もいますが、システムに共有データベースがあれば、他の賢い使い方も見つかると思います。

ボーナスとして、監査可能性が得られます。変更の履歴はテーブルに記録できます。

于 2012-01-18T19:41:48.857 に答える