退出python中的所有模块
我在写一个代码,其中有各种功能。我为每个特定功能创建了.py文件,并在需要时导入它们。示例代码:退出python中的所有模块
# 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命令在控制台上打印任何东西。正如我在另一个项目中曾经使用过sys.exit()一样,它会在控制台上打印出我不需要的警告,因为该项目适用于不了解警告是什么的人。
如果我使用exit命令结束的代码,会什么时候结束整个执行
是的,它会(假设你的意思sys.exit()
)。
或只是游戏模块
不,这将退出整个程序。
感谢它的工作。 –
如果你担心sys.exit()
“显示警告”(我不能在我的系统上确认 - 应用程序只是存在并且打印在控制台没有警告),你只需提高SystemExit
与艇员选拔的消息:
raise SystemExit("Everything is fine.")
伟大的建议!为此+1。 –
如果要隐藏警告,当程序退出(这个警告可能是堆栈跟踪,很难从你的问题估计),那么你可以尝试换行代码除块:
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
注这个技术que被认为是非常糟糕的,您应该将例外记录到文件中。
十大你的模块用户sys.exit的insend()内使用:
# 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
# suppose you want to exit from here
# dont use sys.exit()
# use
raise Exception("Something went wrong")
Finnaly记录异常到文件
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)
使用此用户将无法看到控制台时,任何消息你的程序意外退出。通过阅读excetions.log文件,您将能够看到发生了什么异常。
如果你想终止您的应用程序,你可以使用''sys.exit()'' - [文件](HTTPS: //docs.python.org/3.6/library/constants.html#exit)。附注:您应该考虑通过使用函数来构造您的代码。 –
我也在函数中构造了我的代码,它工作正常。但是因为我的代码有800行以上的大小,所以我需要制作一个相同的库,因为它有不同的阶段。 –
此外,sys.exit()打印出我不想打印在控制台上的警告,因为该项目将用于非技术人员。 –