我如何退出一个脚本早,像die()命令在PHP?
当前回答
我的意见。
Python 3.8.1, Windows 10, 64位。
Sys.exit()不直接为我工作。
我有几个下一个循环。
首先,我声明一个布尔变量,我称之为immediateExit。
因此,在程序代码的开头我写:
immediateExit = False
然后,从最内部(嵌套)循环异常开始,我写道:
immediateExit = True
sys.exit('CSV file corrupted 0.')
然后我进入外层循环的直接延续,在代码执行其他任何东西之前,我写道:
if immediateExit:
sys.exit('CSV file corrupted 1.')
根据复杂程度,有时上述语句也需要在except部分中重复,等等。
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
自定义消息也用于我个人的调试,这些数字也是出于同样的目的——查看脚本真正退出的位置。
'CSV file corrupted 1.5.'
在我的特殊情况下,我正在处理一个CSV文件,我不希望软件触摸,如果软件检测到它已损坏。因此,对我来说,在检测到可能的损坏后立即退出整个Python脚本是非常重要的。
遵循渐进的系统。从所有的循环中退出,我设法做到了。
完整代码:(需要做一些更改,因为它是内部任务的专有代码):
immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date
end_date_in_working_days = False
while not end_date_in_working_days:
try:
end_day_position = working_days.index(end_date)
end_date_in_working_days = True
except ValueError: # try statement from end_date in workdays check
print(current_date_and_time())
end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
print('New end date: ', end_date, '\n')
continue
csv_filename = 'test.csv'
csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
try:
with open(csv_filename, 'r') as file:
print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
last_line = file.readlines()[-1]
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
resumedDate = start_date
if last_line == csv_headers:
pass
elif start_date not in working_days:
print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
immediateExit = True
sys.exit('CSV file corrupted 0.')
else:
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
print('\nLast date:', start_date)
file.seek(0) # setting the cursor at the beginnning of the file
lines = file.readlines() # reading the file contents into a list
count = 0 # nr. of lines with last date
for line in lines: #cycling through the lines of the file
if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
count = count + 1
if immediateExit:
sys.exit('CSV file corrupted 1.')
for iter in range(count): # removing the lines with last date
lines.pop()
print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))
if immediateExit:
sys.exit('CSV file corrupted 1.2.')
with open(csv_filename, 'w') as file:
print('\nFile', csv_filename, 'open for writing')
file.writelines(lines)
print('\nRemoving', count, 'lines from', csv_filename)
fileExists = True
except:
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
with open(csv_filename, 'w') as file:
file.write(csv_headers)
fileExists = False
if immediateExit:
sys.exit('CSV file corrupted 2.')
其他回答
也可以简单地使用exit()。
请记住sys.exit(), exit(), quit()和os._exit(0)会杀死Python解释器。因此,如果它出现在execfile()从另一个脚本调用的脚本中,它将停止两个脚本的执行。
请参见“停止执行使用execfile调用的脚本”以避免这种情况。
提前终止Python脚本的一个简单方法是使用内置的quit()函数。不需要导入任何库,而且高效简单。
例子:
#do stuff
if this == that:
quit()
在Python 3.5中,我尝试在不使用模块(例如sys, Biopy)的情况下合并类似的代码,而不是使用内置的停止脚本并向用户打印错误消息的模块。以下是我的例子:
## My example:
if "ATG" in my_DNA:
## <Do something & proceed...>
else:
print("Start codon is missing! Check your DNA sequence!")
exit() ## as most folks said above
后来,我发现抛出一个错误更简洁:
## My example revised:
if "ATG" in my_DNA:
## <Do something & proceed...>
else:
raise ValueError("Start codon is missing! Check your DNA sequence!")
我的意见。
Python 3.8.1, Windows 10, 64位。
Sys.exit()不直接为我工作。
我有几个下一个循环。
首先,我声明一个布尔变量,我称之为immediateExit。
因此,在程序代码的开头我写:
immediateExit = False
然后,从最内部(嵌套)循环异常开始,我写道:
immediateExit = True
sys.exit('CSV file corrupted 0.')
然后我进入外层循环的直接延续,在代码执行其他任何东西之前,我写道:
if immediateExit:
sys.exit('CSV file corrupted 1.')
根据复杂程度,有时上述语句也需要在except部分中重复,等等。
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
自定义消息也用于我个人的调试,这些数字也是出于同样的目的——查看脚本真正退出的位置。
'CSV file corrupted 1.5.'
在我的特殊情况下,我正在处理一个CSV文件,我不希望软件触摸,如果软件检测到它已损坏。因此,对我来说,在检测到可能的损坏后立即退出整个Python脚本是非常重要的。
遵循渐进的系统。从所有的循环中退出,我设法做到了。
完整代码:(需要做一些更改,因为它是内部任务的专有代码):
immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date
end_date_in_working_days = False
while not end_date_in_working_days:
try:
end_day_position = working_days.index(end_date)
end_date_in_working_days = True
except ValueError: # try statement from end_date in workdays check
print(current_date_and_time())
end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
print('New end date: ', end_date, '\n')
continue
csv_filename = 'test.csv'
csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
try:
with open(csv_filename, 'r') as file:
print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
last_line = file.readlines()[-1]
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
resumedDate = start_date
if last_line == csv_headers:
pass
elif start_date not in working_days:
print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
immediateExit = True
sys.exit('CSV file corrupted 0.')
else:
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
print('\nLast date:', start_date)
file.seek(0) # setting the cursor at the beginnning of the file
lines = file.readlines() # reading the file contents into a list
count = 0 # nr. of lines with last date
for line in lines: #cycling through the lines of the file
if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
count = count + 1
if immediateExit:
sys.exit('CSV file corrupted 1.')
for iter in range(count): # removing the lines with last date
lines.pop()
print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))
if immediateExit:
sys.exit('CSV file corrupted 1.2.')
with open(csv_filename, 'w') as file:
print('\nFile', csv_filename, 'open for writing')
file.writelines(lines)
print('\nRemoving', count, 'lines from', csv_filename)
fileExists = True
except:
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
with open(csv_filename, 'w') as file:
file.write(csv_headers)
fileExists = False
if immediateExit:
sys.exit('CSV file corrupted 2.')
我完全是个新手,但这肯定更干净,更可控
def main():
try:
Answer = 1/0
print Answer
except:
print 'Program terminated'
return
print 'You wont see this'
if __name__ == '__main__':
main()
...
程序终止
than
import sys
def main():
try:
Answer = 1/0
print Answer
except:
print 'Program terminated'
sys.exit()
print 'You wont see this'
if __name__ == '__main__':
main()
...
程序终止回溯(最近一次调用):文件“Z:\目录\testdieprogram.py”,第12行,在 main()文件“Z:\目录\testdieprogram.py”,第8行,在main中 SystemExit sys.exit ()
Edit
重点是,该计划顺利和平地结束,而不是“我已经停止!!!!”