2017-07-19 49 views
0

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

控制-C會的工作,如果它是從命令提示符下運行。 – jasonharper

+0

我們目前從PyCharm運行,雖然我認爲它可以讓你啓動某種終端。 – Batman0730

+0

什麼操作系統和Python版本? – phd

回答

0

我發現了PyCharm bug跟蹤解決方法:

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

  • 在PyCharm去h ELP->編輯自定義屬性
  • 同意創建idea.properties文件(如果它要求)
  • 添加以下行:kill.windows.processes.softly =真
  • 如果您使用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 
相關問題