如何在退出时阻止多处理垃圾邮件?

2024-05-21 05:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我肯定这很容易,但我找不到任何问题

我有一堆进程在一个池中运行;当ctrl+c被按下时,我希望程序停止并干净地退出,而不会对每个关闭的进程在屏幕上显示“None”

给定以下测试代码:

#! /usr/bin/env python3

import multiprocessing
import signal

def graceful_close(blah, blah2):
    exit()
signal.signal(signal.SIGINT, graceful_close)

def wait():
    while True:
        pass
try:
    pool = multiprocessing.Pool(20)
    for i in range(1, 20):
        pool.apply_async(wait)
    while True:
        pass
except KeyboardInterrupt:
    exit()

如何防止输出:

[-2019-09-15 21:56:06 ~/git/locane $> ./test_mp_exit_spam.py
^CNone
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
[-2019-09-15 21:56:11 ~/git/locane $>

是什么导致的


Tags: importgitnonetrueclosesignal进程def
1条回答
网友
1楼 · 发布于 2024-05-21 05:47:00

请使用sys.exit而不是exit

exit是交互式shell的助手-sys.exit用于程序中

既然您已经在处理SIGNINT,就不知道为什么需要显式地处理KeyboardInterrupt

import sys
import multiprocessing
import signal

def graceful_close(blah, blah2):
    sys.exit()

signal.signal(signal.SIGINT, graceful_close)

def wait():
    while True:
        pass

pool = multiprocessing.Pool(20)
for i in range(1, 20):
    pool.apply_async(wait)

while True:
    pass

相关问题 更多 >