簡體   English   中英

為什么Python多處理守護進程不能打印到標准輸出?

[英]Why is a Python multiprocessing daemon process not printing to standard output?

我一直在嘗試多處理,並使用守護進程運行到一個mindblock。

我有一個守護進程和一個非守護進程,守護進程每隔一秒無限期地發出輸出,而非守護進程在啟動時立即打印輸出,休眠3秒,然后再次打印並返回。

問題是,守護進程的預期輸出根本沒有顯示出來。

回顧過去關於守護進程的SO問題,常見問題似乎是在守護進程之前結束的其他進程,或者需要刷新以顯示輸出的stdout。 兩者都(我認為 )已得到解決,但我仍然只看到來自非守護進程的打印輸出。

編碼:

from multiprocessing import Process, current_process
import sys
import time

def worker():
    """
    Announce that the process has started, sleep 3 seconds
    then announce that the process is ending.
    """
    name = current_process().name
    print name, 'starting...'
    sys.stdout.flush()

    time.sleep(3)
    print name, 'ending...'
    sys.stdout.flush()

    return


def daemon():
    """
    Announce that the process has started, beep, then beep
    once every second
    """
    name = current_process().name
    print name, 'starting...'
    print 'beep...'
    sys.stdout.flush()

    while True:
        time.sleep(1)
        print 'beep...'
        sys.stdout.flush()


if __name__=='__main__':
    d = Process(target=daemon)
    d.daemon = True
    d.start()

    p = Process(target=worker)
    p.daemon = False
    p.start()

預期產出:

Process-1 starting... # Order here may vary
beep...
Process-2 starting...
beep...
beep...
Process-2 ending... #There may or may not be another beep here

實際生產的內容:

Process-2 starting...
Process-2 ending...

任何關於為什么會發生這種情況的建議都會得到真正的體會

您可以通過放置打開日志來更清楚地了解事件的順序

import multiprocessing as mp
logger = mp.log_to_stderr(logging.INFO)

在其他進口聲明之后。 然后你的程序將產生類似於:

[INFO/Process-1] child process calling self.run()
[INFO/MainProcess] process shutting down
Process-1 starting...
beep...
[INFO/Process-2] child process calling self.run()
[INFO/MainProcess] calling terminate() for daemon Process-1
Process-2 starting...
[INFO/MainProcess] calling join() for process Process-2
Process-2 ending...
[INFO/Process-2] process shutting down
[INFO/Process-2] process exiting with exitcode 0
[INFO/MainProcess] calling join() for process Process-1

因此,主要開始先關閉,然后終止進程-1,即守護進程。 這就是為什么在Process-2繼續時你不會再看到嗶嗶聲的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM