如何停止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