停止Python进程,以便上下文pipe理器仍然调用__exit__(在Windows中)

如何停止python进程,以使任何活动的上下文pipe理器在closures前优雅地调用__exit__函数?

我使用上下文pipe理器(__enter __()和__exit __())来可靠和安全地closures与光学硬件的连接。 尽pipe我们现在开始执行几个小时的程序,但这一直很好。 我们通常会在开始之后不久就意识到我们有一个bug,宁愿停止这个过程。

我一直在运行PyCharm的代码,它允许你“停止”正在运行的进程。 这似乎立即杀死进程,无论我在debugging或运行。 __exit__函数似乎不被调用。

另外,控制硬件的计算机运行窗口,如果它以某种方式发挥作用的话。 ***

***事实上,在发挥作用。 MacOSx似乎调用退出function,而Windows没有。

我决定写一个基本的testing:

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运行这段代码,当它在sleep语句中时,按下pycharm中的停止button。 以下是来自两者的输出:

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 

视窗

 Init called. enter called Process finished with exit code 1 

Solutions Collecting From Web of "停止Python进程,以便上下文pipe理器仍然调用__exit__(在Windows中)"

我在PyCharm bug跟踪器上找到了一个解决方法:

https://youtrack.jetbrains.com/issue/PY-17252

  • 在PyCharm中去帮助 – >编辑自定义属性
  • 同意创建idea.properties文件(如果询问)
  • 添加以下行:kill.windows.processes.softly = true
  • 如果您使用Numpy或Scipy,则还需要添加以下环境变量:

    os.environ ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] =“1”

  • 重新启动Pycharm

现在当我运行这个应用程序(在Windows上)我的测试时,我得到以下输出:

 Init called. enter called Exit called Traceback (most recent call last): File "C:/Users/.../.PyCharmCE2017.1/config/scratches/scratch_3.py", line 20, in <module> time.sleep(100) KeyboardInterrupt Process finished with exit code 1