简体   繁体   English

监控Python并行进程的进度

[英]Monitoring progress in Python parallel processes

The following code returns the error: 以下代码返回错误:

local variable 'count' referenced before assignment.

Below are the two functions: 以下是两个功能:

def run():
    ...
    global count
    count = 0
    with closing(Pool(processes=4)) as pool:
    pool.map(run_in_parallel, listOfIds)
    pool.terminate()
    ...

def run_in_parallel(id):
    count += 1
    if count % 1000 == 0:
        print('Processed %d %s' % (count, time.strftime('%x %X')))
    # Do main work in parallel

The error pops up only because of the modifying statement. 仅由于修改语句而弹出错误。 ie

count +=1

I have read in several places that it is not a good practice to modify global variables in worker processes. 我已经在几个地方读到,在工作进程中修改全局变量不是一个好习惯。 But since the listOfIds is a huge list, I need some way of monitoring progress and printing to terminal once in a while. 但是由于listOfIds是一个庞大的列表,因此我需要某种方式来监视进度并偶尔打印到终端。 How is this to be done? 怎么做?

I have read other posts on StackOverflow and other places and none of the other questions address the exact same problem described above. 我已经阅读了StackOverflow和其他地方的其他文章,其他问题都没有解决上述完全相同的问题。

The error occurs most likely because you were not making the global variable count available via global count , like you did in your run() function. 发生该错误的可能性最大,因为您没有像run()函数那样通过global count使全局变量count可用。

Anyways, this will not work like you want it to work. 无论如何,这不会像您希望的那样工作。 Every spawned process will have it's own global count variable, which it will increment and which will always be 0 at creation time. 每个产生的进程都有自己的全局count变量,该变量将递增,并且在创建时始终为0

If you want to count it like that, you should use the example that Tom Dalton was linking for you: 如果要这样计算,则应使用Tom Dalton为您链接的示例:

import time
from multiprocessing import Process, Value

def func(val):
    for i in range(50):
        time.sleep(0.01)
        val.value += 1

if __name__ == '__main__':
    v = Value('i', 0)
    procs = [Process(target=func, args=(v,)) for i in range(10)]

    for p in procs: p.start()
    for p in procs: p.join()

    print v.value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM