如何停止python進程,以便任何活動上下文管理器在關閉前優雅地調用其__exit__函數?停止python進程,以便上下文管理器仍然調用__exit__(在windows中)
我使用上下文管理器(__enter __()和__exit __())可靠且安全地關閉光學硬件連接。儘管我們現在開始執行運行幾個小時的例程,但這一直很好。通常我們會在開始之後不久意識到有一個bug,並且寧願停止這個過程。
我一直在運行PyCharm的代碼,它允許你「停止」正在運行的進程。這似乎立即殺死進程,無論我在調試還是運行。 __exit__函數似乎沒有被調用。
此外,控制硬件的計算機運行窗口,如果它以某種方式發揮作用。 ***
***確實發揮作用。 Macosx似乎調用退出功能,而窗戶沒有。
我決定寫一個基本的測試:
from abc import *
import time
class Test(object):
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
print("Init called.")
def __enter__(self, *args, **kwargs):
print("enter called")
def __exit__(self, type, value, traceback):
print("Exit called")
with Test() as t:
time.sleep(100)
print("Should never get here.")
我從PyCharm運行此代碼,雖然它處於睡眠聲明我按在pycharm停止按鈕。下面是從兩個輸出:
MACOSX:
Init called.
enter called
Exit called
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1591, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1018, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/.../Library/Preferences/PyCharmCE2017.1/scratches/scratch_25.py", line 22, in <module>
time.sleep(100)
KeyboardInterrupt
的Windows
Init called.
enter called
Process finished with exit code 1
控制-C會的工作,如果它是從命令提示符下運行。 – jasonharper
我們目前從PyCharm運行,雖然我認爲它可以讓你啓動某種終端。 – Batman0730
什麼操作系統和Python版本? – phd