2015-10-05 53 views
1

Python的片斷答:如何在一個python進程中查詢/設置變量形成另一個python進程?

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 

如何查詢,甚至設置task1.progress_percenttask2.progress_percent運行時從另一個單獨的Python進程? (不是pdb)

謝謝。

回答

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} 
+0

感謝您的答覆,但我想知道什麼我是否可以從另一個單獨的「蟒蛇過程」查詢task.progress_percent,有點兒進程之間的「IPC」 –

+0

Ops ..對不起=) 您可以使用共享名稱空間來執行此操作。如果你願意,我可以舉個例子。 – arkadyzalko

+0

讚賞如果你能展示一個例子,更多的可以'共享命名空間'爲不同的python進程工作而不是由進度A產生? –

相關問題