第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

如何正確設(shè)置 sys.excepthook

如何正確設(shè)置 sys.excepthook

米脂 2023-03-16 09:54:59
我編寫了以下代碼來理解多進(jìn)程環(huán)境中的 sys.excepthook。我正在使用 python 3。我創(chuàng)建了 2 個(gè)進(jìn)程,它們將打印并等待獲取 ctrl+c。from multiprocessing import Processimport multiprocessingimport sysfrom time import sleepclass foo:    def f(self, name):        try:            raise ValueError("test value error")        except ValueError as e:            print(e)        print('hello', name)        while True:            passdef myexcepthook(exctype, value, traceback):    print("Value: {}".format(value))    for p in multiprocessing.active_children():        p.terminate()def main(name):    a = foo()    a.f(name)sys.excepthook = myexcepthookif __name__ == '__main__':    for i in range(2):        p = Process(target=main, args=('bob', ))        p.start()當(dāng)我按下時(shí),我期待以下結(jié)果ctrl+Cpython /home/test/test.pytest value errorhello bobtest value errorhello bobValue: <KeyboardInterrupt>但不幸的是,我得到了以下結(jié)果。/home/test/venvPython3/bin/python /home/test/test.pytest value errorhello bobtest value errorhello bobError in atexit._run_exitfuncs:Traceback (most recent call last):Process Process-1:  File "/usr/lib/python3.6/multiprocessing/popen_fork.py", line 28, in poll    pid, sts = os.waitpid(self.pid, flag)KeyboardInterruptTraceback (most recent call last):  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap    self.run()  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run    self._target(*self._args, **self._kwargs)  File "/home/test/test.py", line 26, in main    a.f(name)  File "/home/test/test.py", line 15, in f    passKeyboardInterruptProcess Process-2:Traceback (most recent call last):  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap    self.run()  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run    self._target(*self._args, **self._kwargs)  File "/home/test/test.py", line 26, in main    a.f(name)  File "/home/test/test.py", line 15, in f    passKeyboardInterruptProcess finished with exit code 0如果有人能指出我做錯(cuò)了什么,那將是一個(gè)很大的幫助。另外,請讓我知道如何獲得預(yù)期的輸出。
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

你幾乎做到了。首先,使用exctype打?。?/p>


def myexcepthook(exctype, value, traceback):

    print("Value: {}".format(exctype))

    for p in multiprocessing.active_children():

        p.terminate()

并join()創(chuàng)建流程,防止過早退出


if __name__ == '__main__':

    pr = []

    for i in range(2):

        p = Process(target=main, args=('bob', ))

        p.start()

        pr.append(p)

    for p in pr:

        p.join()


查看完整回答
反對 回復(fù) 2023-03-16
  • 1 回答
  • 0 關(guān)注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號