从python中的所有模块退出

2024-03-28 23:32:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个代码,里面有各种各样的函数。我为每个特定函数创建了.py文件,并在需要时导入它们。示例代码:

# main.py file
import addition
import subtraction
a = input("enter a")
b = input("enter b")
c = input("enter 1 to add 2 to subtract")
if a == 1:
    addition.add(a, b)  # call to add function in addition module
    subtraction.minus(a, b) # call to subtract function in subtraction module
# More code here

# addition.py module
import game # import another self-created module
y = input("do you want to play a game? Enter 1 if yes and 0 if no")
if y == 1:
    game.start()
# more similar code

我现在可以看到在多个级别调用模块。所以我的问题是在我的game模块中,如果我使用exit命令来结束代码,它会结束整个执行还是仅仅是game模块? 当我在代码中遇到异常时,我需要一个命令来退出整个代码的执行。在

注意:我不希望exit命令在控制台上打印任何内容。就像我以前那样系统出口()以前在另一个项目中,它在控制台上打印警告,我不需要它,因为这个项目是为那些不了解警告是什么的人准备的。在


Tags: 模块to函数代码pyimport命令add
3条回答

if I use exit command to end the code, will it end the whole execution

是的,它会的(假设你的意思是sys.exit())。在

or just the game module

不,它会退出整个程序。在

如果您想在程序退出时隐藏警告(此警告可能是堆栈跟踪,很难从您的问题中猜测),那么可以将代码包装在try except块中:

 import addition
 import subtraction
 try:   
    a = input("enter a")
    b = input("enter b")
    c = input("enter 1 to add 2 to subtract")
    if a == 1:
        addition.add(a, b)  # call to add function in addition module
        subtraction.minus(a, b) # call to subtract function in subtraction module
    # ...
except Exception:
    pass

请注意,这种技术被认为是非常糟糕的,您可能应该将异常记录到文件中。在

在你的模块里面有10个用户系统出口()使用这个:

^{pr2}$

最终记录文件的异常

import addition
import subtraction
import logging

# log to file
logging.basicConfig(filename='exceptions.log',level=logging.DEBUG)
try:
    a = input("enter a")
    b = input("enter b")
    c = input("enter 1 to add 2 to subtract")
    if a == 1:
        addition.add(a, b)  # call to add function in addition module
        subtraction.minus(a, b) # call to subtract function in subtraction module
    # ...
except Exception as e:
    logging.exception(e)

使用此选项,当程序意外退出时,用户将看不到控制台上的任何消息。通过阅读,您将能够看到发生了哪些异常异常.log文件。在

更多信息

你不能在我的控制台上显示警告信息

raise SystemExit("Everything is fine.")

相关问题 更多 >