而不杀死Python进程
停止Python脚本,我想知道是否有一种编程停止python脚本执行而不杀死进程像我们做这个代码的方式:而不杀死Python进程
import sys
sys.exit()
这将是代码相当于按Ctrl + C
定义自己的异常,
class HaltException(Exception): pass
和
包裹脚本try:
# script goes here
# when you want to stop,
raise HaltException("Somebody stop me!")
except HaltException as h:
print(h)
# now what?
谢谢你理解这个问题,的确解决了这个问题 – 2015-02-09 15:38:47
你也可以将你的整个代码封装在函数中(不要忘记main()和if __name__ =='__main__'stuff),那么当你想退出时,返回一个随机值 – 2015-02-09 15:39:35
这是我发现的工作 - 停留在解释器中,同时停止脚本。
# ------------------------------------------------------------------
# Reset so get full traceback next time you run the script and a "real"
# exception occurs
if hasattr (sys, 'tracebacklimit'):
del sys.tracebacklimit
# ------------------------------------------------------------------
# Raise this class for "soft halt" with minimum traceback.
class Stop (Exception):
def __init__ (self):
sys.tracebacklimit = 0
# ==================================================================
# ... script here ...
if something_I_want_to_halt_on:
raise Stop()
# ... script continues ...
我在开发Sublime Text包时遇到了这个问题。我试图阻止一个Sublime Text Python包,在包被重新加载时测试一些东西。
如果我打电话sys.exit()
,我杀死了Sublime Text python解释器,并需要重新启动Sublime Text。但搜索后,我想通了该解决方案是非常简单的,我只需要调用raise ValueError()
,而不是sys.exit()
:
import sys
print(sys.path)
sys.exit()
- >
import sys
print(sys.path)
raise ValueError()
这将停止python脚本执行权后运行print(sys.path)
。虽然它会打印一个大堆栈跟踪。但是,如果你raise ValueError()
前添加指令sys.tracebacklimit = 1
,可以减少堆栈跟踪呼叫一行:
import sys
print(sys.path)
raise ValueError()
- >
import sys
print(sys.path)
sys.tracebacklimit = 1
raise ValueError()
相关的问题:
我重新发布从here 我的答案,因为它应该解决您的问题,以及只要你的交互shell是IPython的。它会...
- 不杀退出内核
- 没有显示追踪
- 不会强迫你巩固与尝试/节选
- 带或不带IPython的工作代码,无需更改代码
只需从下面的代码中将'exit'导入到脚本中,您也可以使用IPython运行并调用'exit()'。
"""
# ipython_exit.py
Allows exit() to work if script is invoked with IPython without
raising NameError Exception. Keeps kernel alive.
Use: import variable 'exit' in target script with
'from ipython_exit import exit'
"""
import sys
from io import StringIO
from IPython import get_ipython
class IpyExit(SystemExit):
"""Exit Exception for IPython.
Exception temporarily redirects stderr to buffer.
"""
def __init__(self):
# print("exiting") # optionally print some message to stdout, too
# ... or do other stuff before exit
sys.stderr = StringIO()
def __del__(self):
sys.stderr.close()
sys.stderr = sys.__stderr__ # restore from backup
def ipy_exit():
raise IpyExit
if get_ipython(): # ...run with IPython
exit = ipy_exit # rebind to custom exit
else:
exit = exit # just make exit importable
如果 “停止” 你的意思是 “暂停,后面继续的可能性”,尝试的raw_input''或'进口PDB( “按回车键继续。”); pdb.set_trace()'。 – Kevin 2015-02-09 15:23:14
'Ctrl + C'抛出一个'KeyboardInterrupt'异常,如果没有被捕获,则会终止该过程。所以我不确定'sys.exit'应该有多大的不同。 – 2015-02-09 15:25:22
此外,Python是一种解释型语言,这就是为什么停止执行脚本意味着停止执行解释器 – ForceBru 2015-02-09 15:26:44