如何在一个python进程中查询/设置变量形成另一个python进程?

时间:2015-10-05 04:44:51

标签: python process ipc

Python代码段A:

import time

class task:
    def __init__(self): 
        self.progress_percent = 0

    def working(self):
        self.progress_percent = self.progress_percent + 1    
task1 = task()
task2 = task()

while True:
    time.sleep(1)
    task1.working()
    task2.working()    
    print task1.progress_percent
    print task2.progress_percent

如何从另一个单独的python进程查询甚至设置task1.progress_percenttask2.progress_percent运行时? (不是pdb)

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用multiprocessing.Process和Condition来执行此操作。请尝试以下代码:

import multiprocessing

import time

class Task(multiprocessing.Process):
    counter = 0
    name = None
    event = None
    another_tasks = set()
    def __init__(self, mgr_dict, cond): 
        super(Task, self).__init__()
        self.mgr_dict = mgr_dict
        self.cond = cond
        cls = self.__class__
        cls.counter += 1
        self.name = '{} {}'.format(cls.__name__, cls.counter)
        self.mgr_dict[self.name] = 0

    def value(self):
        return self.mgr_dict[self.name]

    def run(self):
        while True:
            with self.cond:
                self.cond.wait()
                self.mgr_dict[self.name] += 1

class SubTask(Task):
    pass

class MainTask(Task):
    subtasks = set()
    def working(self):
        with self.cond:
            self.cond.notify_all()

    def start(self):
        super(MainTask, self).start()
        for subtask in self.subtasks:
            subtask.start()

    def create_subtask(self):
        subtask = SubTask(self.mgr_dict, condition)
        self.subtasks.add(subtask)

    def join(self):
        self.mgr_dict[self.name]

    def shutdown(self):
        self.exit.set()

event = multiprocessing.Event()
if __name__ == '__main__':
    mgr = multiprocessing.Manager()
    mgr_dict = mgr.dict()

    condition = multiprocessing.Condition()
    task1 = MainTask(mgr_dict, condition)
    subtask1 = task1.create_subtask()
    subtask2 = task1.create_subtask()
    subtask3 = task1.create_subtask()
    subtask4 = task1.create_subtask()
    subtask5 = task1.create_subtask()
    task1.start()
    while task1.value() < 100:
        time.sleep(1)
        task1.working()
        print mgr_dict

结果:

{'MainTask 1': 0, 'SubTask 1': 0, 'SubTask 2': 0, 'SubTask 3': 0, 'SubTask 4': 0, 'SubTask 5': 0}
{'MainTask 1': 1, 'SubTask 1': 1, 'SubTask 2': 1, 'SubTask 3': 1, 'SubTask 4': 1, 'SubTask 5': 1}
.
.
.
{'MainTask 1': 100, 'SubTask 1': 100, 'SubTask 2': 100, 'SubTask 3': 100, 'SubTask 4': 100, 'SubTask 5': 100}