Eclipse+Pydev:“清理” 按“停止”时不会调用函数?
尝试在 Eclipse 中运行此文件
class Try:
def __init__(self):
pass
def __del__(self):
print 1
a=Try()
raw_input('waiting to finish')
并按停止按钮而不让程序完成不会打印“1”,即永远不会调用 del 方法。 如果我尝试从 shell 运行脚本并执行 ctrl-c\sys.exit "1" 确实会打印出来,即调用 del 。 如果我尝试使用 wait() 也会发生同样的情况:
class A:
def __enter__(self):
return None
def __exit__(self, type, value, traceback):
print 3
with A():
print 1
raw_input('Waiting')
print 2
如果我在提示时按“停止”,则不会打印“3”
这是为什么? 有办法解决吗?
谢谢,诺姆
Trying to run this file in eclipse
class Try:
def __init__(self):
pass
def __del__(self):
print 1
a=Try()
raw_input('waiting to finish')
and pressing the stop button without letting the program finish doesn't print "1", i.e the del method is never called. If i try to run the script from the shell and do ctrl-c\sys.exit "1" does get printed i.e del is called.
Same thing if I try to use wait():
class A:
def __enter__(self):
return None
def __exit__(self, type, value, traceback):
print 3
with A():
print 1
raw_input('Waiting')
print 2
If i press "stop" when prompted, "3" isn't printed
Why is that?
Is there a way around it?
Thanks, Noam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 文档:
如果要保证调用方法,请使用with 语句
Python docs:
If you want to guarantee that a method is called use the with-statement
在 Eclipse 中直接按下 stop 会终止解释器(尽管它实际上经常失败)。 就像使用
kill
/taskkill
一样,进程不知道它的终止。Ctrl+C 来自维基百科的片段...
Ctrl+C
是中断程序的控制信号,但正如您可能在该段中间注意到的那样,程序可以指定如何处理该信号。 在 Python 中,Ctrl+C 抛出一个 KeyboardInterrupt 异常,该异常通常会被捕获,然后Python 干净地退出。 即使您使用 Ctrl+C 终止解释器,它也可能会处理它,以便在退出之前清理环境。我添加以下内容是因为您问“有解决办法吗?”
如果您想停止
raw_input(...)
调用,可以使用Ctrl+Z
发送 EOF。 我环顾四周,不幸的是,似乎没有办法在 Eclipse 中发送Ctrl+C
/0x03
。Pressing stop in Eclipse outright kills the interpreter (though it actually fails fairly often). Like using
kill
/taskkill
, the process is unaware of it's demise.Ctrl+C snippet from Wikipedia...
Ctrl+C
is a control signal to interrupt the program, but as you may have noticed in the middle of that paragraph, programs can specify how to handle the signal. In Python, Ctrl+C throws a KeyboardInterrupt exception which is normally caught and then Python exits cleanly. Even if you're killing the interpreter withCtrl+C
it may handle it so that it cleans the environment before exiting.I included the following because you asked "Is there a way around it?"
If you are wanting to stop on
raw_input(...)
calls, you could useCtrl+Z
to send EOF. I looked around, and there seems to be no way to sendCtrl+C
/0x03
in Eclipse, unfortunately.