Python的“ progress”模块未在函数中显示来自os.fork()的微调器

时间:2019-08-15 22:47:23

标签: python-3.x function fork progress

我想使用progress模块,但是,旋转器似乎在函数内的os.fork()内部不起作用。例如:

import sys, time, signal, os
from progress.spinner import MoonSpinner


def spinner_func():
    spinner = MoonSpinner('this is a test')
    pid = os.fork()
    if pid == 0:
        while True:
            time.sleep(0.1)
            spinner.next()
        exit()

    # Some long-running, blocking action would normally go here
    time.sleep(20)

    os.kill(pid, signal.SIGTERM)
    spinner.finish()
    print('Done!!')

同一代码在外部函数中起作用,因为它显示了微调器,直到执行结束。我不确定如何在函数中使用此模块,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

“ spinner”变量必须在子进程内部分配,并且可以通过multiprocessing.Queue()发送给父进程

例如:

import sys, time, signal, os, multiprocessing
from progress.spinner import MoonSpinner


def spinner_func():
    q = multiprocessing.Queue()
    pid = os.fork()
    if pid == 0:
        spinner = MoonSpinner('this is a test') # <<--notify
        q.put(spinner)
        while True:
            time.sleep(0.1)
            spinner.next()
        exit()

    time.sleep(20)
    os.kill(pid, signal.SIGTERM)
    spinner = q.get()
    spinner.finish()
    print('Done!!')

spinner_func()