導航:首頁 > 編程語言 > 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捕捉子方法的異常相關的資料

熱點內容
編譯怎麼學 瀏覽:329
數碼管顯示0到9plc編程 瀏覽:665
伺服器是為什麼服務的 瀏覽:765
java定義數據類型 瀏覽:874
安卓pdf手寫 瀏覽:427
什麼是app開發者 瀏覽:284
android鬧鍾重啟 瀏覽:101
程序員失職 瀏覽:518
在雲伺服器怎麼改密碼 瀏覽:586
伺服器pb什麼意思 瀏覽:940
51駕駛員的是什麼app 瀏覽:670
php靜態變數銷毀 瀏覽:886
編程買蘋果電腦 瀏覽:760
flac演算法 瀏覽:497
reactnative與android 瀏覽:663
程序員是干什麼的工作好嗎 瀏覽:258
kbuild編譯ko 瀏覽:469
條件編譯的宏 瀏覽:564
韓語編程語言 瀏覽:646
小程序開發如何租用伺服器 瀏覽:80