導航:首頁 > 編程語言 > python捕捉子方法的異常

python捕捉子方法的異常

發布時間:2023-10-29 18:47:20

python中主線程怎樣捕獲子線程的異常

最近因為別的需求,寫了一個模塊,似乎在這里能用得上:

https://github.com/SakuraSa/ChatProcess


其中的 example.py :

#!/usr/bin/envpython
#coding=utf-8

"""
example
"""

__author__='Rnd495'

fromtimeimportsleep
fromChatProcessimportChatroom


classEcho(Chatroom):
"""
Echo
"""
defresponse(self,data):
ifdata.startswith('sleep'):
sec=float(data[6:])
sleep(sec)
return'wakeupafter%dms'%(sec*1000)
elifdata:
returndata
else:
self.stop()
return'goodbye'


if__name__=='__main__':
,ProcessError

print'process01:'
e=Echo.create_process(lifetime=1).start()
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:0.1'),e.remain
printe.chat(''),e.remain

print''
print'process02:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:1.0'),e.remain
printe.chat(''),e.remain
exceptTimeoutError,error:
print'error:',error

print''
print'process03:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:notanum'),e.remain
printe.chat(''),e.remain
exceptProcessError,error:
print'error:',error


運行結果為:

process01:
Helloworld!0.773000001907
wakeupafter100ms0.549000024796
goodbye0.547000169754

process02:
Helloworld!0.868000030518
error:TimeoutError

process03:
Helloworld!0.868000030518
error:('Erroroccurredonloop',ValueError('couldnotconvertstringtofloat:notanum',))


在其中的 process01 中,主進程捕獲了 超時

在其中的 process02 中,主進程捕獲了 子進程的錯誤


不知道你能不能用得上

閱讀全文

與python捕捉子方法的異常相關的資料

熱點內容
高數第六版下冊答案pdf 瀏覽:899
sm3演算法實現java 瀏覽:669
只有程序員才懂的笑話 瀏覽:264
php開發app介面源碼 瀏覽:6
加密狗寶寶 瀏覽:231
單片機搶答器的原理 瀏覽:922
百利達體脂儀可以用什麼app連接 瀏覽:220
伺服器2016自動備份怎麼取消 瀏覽:838
dos攻擊命令大全 瀏覽:842
夢世界伺服器怎麼擴大領地 瀏覽:968
解壓breathe 瀏覽:433
webview調用java 瀏覽:348
android待機流程 瀏覽:856
python直接退出程序 瀏覽:848
百戰程序員收費標准 瀏覽:778
時鍾置換演算法指針變化規則 瀏覽:250
微信加密能否改密碼 瀏覽:109
android許可權組 瀏覽:175
2017單片機 瀏覽:481
讓孩子感興趣編程的電影 瀏覽:264