2017-09-25 114 views
0

我想使用多處理包從多個來源讀取帶有JSON的數據。我也想無限期地去做。無限循環內的多處理

這裏是我的代碼文本:

while True: 
 
\t time_start = datetime.datetime.now() 
 
\t f = open("data_logging_pv.csv", "ab") 
 
\t c = csv.writer(f) 
 
\t if __name__ == '__main__': 
 
\t  p=Pool(6) 
 
\t  output = p.map(getData, [2, 4, 5, 6, 7, 9]) 
 
\t  j = 0 
 
\t  for i in [2, 4, 5, 6, 7, 9]: 
 
\t \t  c.writerow([time_start, i, output[j][0], output[j][1], output[j][2], output[j][3], output[j][4]]) 
 
\t \t  j = j + 1; 
 
\t  print(output) 
 
\t  print("\nTemps d'execution:" +str(datetime.datetime.now()-time_start)) 
 
\t  f.close() 
 
\t  p.terminate()

其中,函數的getData是JSON請求。

執行沒有實現p.map,但進程是很好創建的。 我不知道如何調試。

我用python有點生疏,並且已經使用了多處理,那麼可能會出現一些'基本'錯誤。

謝謝 Martin。

+0

我忘了提及循環不是無限的,代碼實際上是即使執行時間隨着迭代次數的增加而增加,也是如此。 –

+0

你使用哪個python版本,以及getData的哪種JSON返回? –

+0

V2.7,並不確定完全理解你想要什麼,但getData返回一個包含5個值的數組。 –

回答

0
    只有一次

不知道

  • 新增一個KeyboardInterrupt處理程序,所以它不會垃圾郵件異常轉換成標準輸出
  • 小優化的CSV寫
  • 池初始化,那種錯誤的你是否也有,但是這代碼片段在python2.7上正常運行:

    import csv 
    import datetime 
    import signal 
    from multiprocessing.pool import Pool 
    
    
    def getData(item): 
        return [item, item + 1, item ** item, item * 2, 0] 
    
    
    def worker(): 
        signal.signal(signal.SIGINT, signal.SIG_IGN) 
    
    
    if __name__ == '__main__': 
    
        time_start = datetime.datetime.now() 
        file = open("data_logging_pv.csv", "ab") 
        c = csv.writer(file) 
        pool = Pool(6, initializer=worker) 
    
        try: 
    
         while True: 
          output = pool.map(getData, [2, 4, 5, 6, 7, 9]) 
    
          for i, res in zip([2, 4, 5, 6, 7, 9], output): 
           c.writerow([str(datetime.datetime.now()), i] + res) 
    
        except KeyboardInterrupt: 
         exit() 
        finally: 
         pool.terminate() 
         pool.join() 
         print("\nTemps d'execution:" + str(datetime.datetime.now() - time_start)) 
         file.close() 
    
  • +0

    看起來不錯。我需要找到更新信息。 –