我有这个尝试/除了代码:
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
打印“[filename]不存在”后如何退出程序? break
和pass
显然不起作用,我不希望出现任何崩溃错误,因此sys.exit
不是一个选项。
请忽略try
部分 - 它只是一个假人。
答案 0 :(得分:25)
使用sys.exit:
import sys
try:
# do something
except Exception, e:
print >> sys.stderr, "does not exist"
print >> sys.stderr, "Exception: %s" % str(e)
sys.exit(1)
一个好的做法是打印出现的异常,以便以后进行调试。
您还可以使用traceback
模块打印堆栈跟踪。
请注意,您在sys.exit中返回的int将是程序的返回码。要查看程序返回的退出代码(这将为您提供有关已发生的事件和可自动化的信息),您可以执行以下操作:
echo $?
答案 1 :(得分:8)
使用
sys.exit(1)
不是崩溃错误,退出程序是一种非常正常的方法。退出代码1是一个约定意味着出错(在成功运行的情况下你会返回0)。
答案 2 :(得分:7)
您还可以将代码放入函数中并发出返回。您可以将其称为main,您可以从脚本中调用它。
def main():
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
return
if __name__ == "__main__":
main()
答案 3 :(得分:5)
重新加注吧。它对开发人员来说更友好了
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
raise
在“提升例外”部分中查看except
中有关重新引发错误的python document。
答案 4 :(得分:3)
如果您在if
内使用try
语句,则需要多个sys.exit()
才能真正退出该程序。
例如,您在调用某个文件的执行时正在解析一个参数,例如$./do_instructions.py 821
,例如:
import sys
# index number 1 is used to pass a set of instructions to parse
# allowed values are integer numbers from 1 to 4, maximum number of instructions is 3
arg_vector = "821" # <- pretending to be an example of sys.argv[1]
if len(arg_vector) > 3:
sys.exit(2) # <- this will take you out, but the following needs an extra step.
# for an invalid input (8).
for i in arg_vector:
# to validate that only numbers are passed as args.
try:
int(i) # <- 8 is valid so far
# value (8) is not valid, since is greater than 4
if (int(i) == 0) or (int(i) > 4):
print("Values must be 1-4")
# the following call does not takes you out from the program,
# but rise the SystemExit exception.
sys.exit(2)
except SystemExit: # <- needed to catch the previous as the first evaluation
# The following parameter "2" is just for this example
sys.exit(2) # <- needed to actually interrupt the execution of the program/script.
# if there is no "except SystemExit:", the following will be executed when the
# previous "if" statement evaluates to True and the sys.exit(2) is called.
#
# and the "print("Only num...") function will be called, even when the intention
# of it is to advice the *user* to use only numbers, since 8 is a number this
# shouldn't be executed.
except:
print("Only numbers are allowed.")
sys.exit(2)
否则,您要对每个评估使用一个 try-except 块。
答案 5 :(得分:0)
可能不是最佳做法,但对我有用:
import sys
close = False
try:
if SomethingBadHappend:
close = True
except:
pass
if close:
sys.exit(1)
接近剂量似乎在“尝试”中不起作用。