gpt4 book ai didi

python - 配置 Python 解释器,使其在一个命令失败时停止执行一系列命令

转载 作者:行者123 更新时间:2023-11-28 22:25:10 24 4
gpt4 key购买 nike

我有时会粘贴要在 Python 解释器中执行的命令列表 ( Interactive Mode ( mirror ))。默认情况下,如果一个命令失败(即引发错误),Python 解释器会指示该命令失败,然后执行后续命令。

有什么方法可以配置 Python 解释器(交互模式),以便在一个命令失败时停止执行一系列命令?


回复评论:

  • 我对 Linux、Mac OS X 和 Microsoft Windows 很感兴趣。
  • 我在 Python 解释器中粘贴的代码示例:

    1/0
    print('yo')

    我不想打印 yo,因为 1/0 会引发错误。

  • 我将命令列表从剪贴板粘贴到 Python 解释器

最佳答案

您可以扩展 InteractiveConsole并创建你自己的 shell,它可以在错误时退出。您甚至可以在交互模式下运行它 :)

这是一个小例子:

from code import InteractiveConsole
import sys


class Shell(InteractiveConsole):
def __init__(self):
self.stdout = sys.stdout
InteractiveConsole.__init__(self)
return

def runcode(self, code):
try:
exec code in self.locals
except:
self.showtraceback()
sys.exit(1) # <-- this is the secret sauce!


if __name__ == '__main__':
sh = Shell()
sh.interact()

输出

>>> sh = Shell()
>>> sh.interact()
Python 2.7.6 (default, Jan 26 2016, 22:37:40)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(Shell)
>>> 1
1
>>> 1+1
2
>>> 1/0
Traceback (most recent call last):
File "<console>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
alfasi:~/Desktop >

关于python - 配置 Python 解释器,使其在一个命令失败时停止执行一系列命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com