當我按CTRL + C取消正在運行的Python腳本時,是否有腳本終止前運行某個python代碼的方法?當取消Python腳本時,做點什麼
2
A
回答
6
使用try/except
捕捉要KeyboardInterrupt
,這是引發當您按下CTRL +Ç。
這是一個基本的腳本來演示:
try:
# Main code
while True:
print 'hi!'
except KeyboardInterrupt:
# Cleanup/exiting code
print 'done!'
這將持續打印'hi!'
直到你按下CTRL +Ç。然後,它打印'done!'
並退出。
0
try:
# something
except KeyboardInterrupt:
# your code after ctrl+c
1
CTRL + C提高KeyboardInterrupt
。你可以捕捉它就像任何其他異常:
try:
main()
except KeyboardInterrupt:
cleanup()
如果你真的不喜歡,你還可以使用atexit.register
註冊清理操作運行(前提是你不要做一些令人頭痛和原因解釋退出的一個時髦的方式)
+0
'atexit.register'是一個很好的選擇。 – SethMMorton
0
此代碼
import time
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
print "Any clean"
給
[email protected] ~/tmp $ python test.py
^CAny clean
當我執行時按Ctrl+C
。
你只需要處理KeyboardInterrupt異常。
此外,你可以處理signals設置處理程序。
0
我很確定你只需要一個try/finally
塊。
試試這個腳本:
import time
def main():
try:
while True:
print("blah blah")
time.sleep(5)
except KeyboardInterrupt:
print("caught CTRL-C")
finally:
print("do cleanup")
if __name__ == '__main__':
main()
輸出應該是這樣的:
blah blah
caught CTRL-C
do cleanup
相關問題
- 1. Python腳本每天在同一時間做點什麼
- 2. 運行python腳本什麼也不做
- 3. 當秒來x時,做點什麼
- 4. AxAcroPdf當加載時,做點什麼
- 5. Android:AlertDialog取消時做些什麼
- 6. Python - 腳本失敗時撤消腳本
- 7. 爲什麼當我導入時,我的python unittest腳本調用我的腳本?
- 8. 當文本評論不會做什麼時使用什麼?
- 9. 只有當沒有輸入焦點時才做點什麼
- 10. 當按鈕點擊兩次時做點什麼
- 11. 取消當調整大小腳本中
- 12. 運行python腳本的最佳做法是什麼?
- 13. y_p ::: python在這個(或任何)腳本中做什麼?
- 14. 這個腳本是做什麼的?
- 15. '^'在批處理腳本中做什麼
- 16. 這個awk腳本是做什麼的?
- 17. 這個腳本是做什麼的?
- 18. 這個腳本是做什麼的?
- 19. 什麼是此行的shell腳本做
- 20. 「\」在PHP/MySQL腳本中做什麼
- 21. 這個awk腳本是做什麼的?
- 22. 描述,告訴腳本做什麼
- 23. 這個shell腳本是做什麼的?
- 24. 這個腳本是做什麼的?
- 25. 這個腳本在做什麼?
- 26. Shell - 這個腳本在做什麼?
- 27. 這個腳本是做什麼的?
- 28. Watir和Rspec腳本什麼都不做
- 29. 這個bash腳本是做什麼的?
- 30. Shell:這個腳本是做什麼的?
您可以趕上'KeyboardInterrupt'錯誤;或者你可以設置[信號處理程序](http://stackoverflow.com/a/1112350/344643);或者你可以在退出時做些事情[使用atexit模塊](http://docs.python.org/2/library/atexit.html#atexit-example)。 –