我如何退出一个脚本早,像die()命令在PHP?
当前回答
只要把quit()放在代码的末尾,就可以关闭一个python脚本。
其他回答
在Python 3.9中,你也可以使用:raise SystemExit("Because I said so")。
from sys import exit
exit()
作为参数,您可以传递一个退出码,该退出码将返回给操作系统。默认值为0。
我刚刚发现,在编写多线程应用程序时,引发SystemExit和sys.exit()都只杀死正在运行的线程。另一方面,os._exit()退出整个进程。这在“为什么在Python线程中调用sys.exit()时不退出?”中讨论过。
下面的例子有两个线程。肯尼和卡特曼。卡特曼应该永远活着,但肯尼被递归调用,应该在3秒后死亡。(递归调用不是最好的方式,但我有其他原因)
如果我们也想让卡特曼在肯尼死的时候死,肯尼就应该带着os走。退出,否则,只有肯尼会死,卡特曼会永生。
import threading
import time
import sys
import os
def kenny(num=0):
if num > 3:
# print("Kenny dies now...")
# raise SystemExit #Kenny will die, but Cartman will live forever
# sys.exit(1) #Same as above
print("Kenny dies and also kills Cartman!")
os._exit(1)
while True:
print("Kenny lives: {0}".format(num))
time.sleep(1)
num += 1
kenny(num)
def cartman():
i = 0
while True:
print("Cartman lives: {0}".format(i))
i += 1
time.sleep(1)
if __name__ == '__main__':
daemon_kenny = threading.Thread(name='kenny', target=kenny)
daemon_cartman = threading.Thread(name='cartman', target=cartman)
daemon_kenny.setDaemon(True)
daemon_cartman.setDaemon(True)
daemon_kenny.start()
daemon_cartman.start()
daemon_kenny.join()
daemon_cartman.join()
我的意见。
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.')
而您通常应该更喜欢sys。退出,因为它对其他代码更“友好”,它实际上所做的只是引发一个异常。
如果你确定你需要立即退出一个进程,并且你可能处于某个异常处理程序中,这个异常处理程序会捕获SystemExit,那么还有另一个函数——os。_exit——它在C级立即终止,不执行任何正常的解释器分解;例如,在"atexit"模块中注册的钩子不会被执行。