我如何退出一个脚本早,像die()命令在PHP?
当前回答
我完全是个新手,但这肯定更干净,更可控
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
重点是,该计划顺利和平地结束,而不是“我已经停止!!!!”
其他回答
在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.')
import sys
sys.exit()
详细信息来自sys模块文档:
sys.exit ((arg)) 退出Python。这是通过提高 SystemExit异常,因此清理操作由finally子句指定 的try语句被执行,并且可以拦截 试图从外部退出。 可选参数arg可以是给出退出状态的整数 (默认为0),或其他类型的对象。如果是整数, 零被认为是“成功终止”,任何非零值都是 shell等认为是“异常终止”。大多数系统 要求它在0-127的范围内,并产生未定义的结果 否则。一些系统有分配特定 具体退出码的含义,但这些通常是 不发达;Unix程序通常使用2作为命令行语法 Errors和1表示所有其他类型的错误。如果是其他类型的对象 传递,None等效于传递零,而任何其他对象是 打印到stderr并导致退出代码为1。特别是, sys。Exit ("some error message")是一种快速退出程序的方法 出现错误。 由于exit()最终“仅”引发异常,因此它只会退出 进程从主线程调用,而异常不是 拦截。
注意,这是一种“不错”的退出方式。下面的@glyphtwistedmatrix指出,如果你想要一个“硬退出”,你可以使用os._exit(*errorcode*),尽管在某种程度上它可能是特定于os的(例如,它可能不会在windows下接受errorcode),而且它肯定不太友好,因为它不让解释器在进程死亡之前做任何清理。另一方面,它会杀死整个进程,包括所有正在运行的线程,而sys.exit()(就像它在文档中说的那样)只在主线程调用时退出,没有其他线程在运行。
另一种方法是:
raise SystemExit
问题
在我的实践中,甚至有一种情况需要从其中一个进程中杀死整个多处理器应用程序。
如果您的应用程序使用唯一的主进程,那么以下函数可以很好地工作。但是在我的例子中,下列函数没有一个不能工作,因为应用程序还有许多其他活动进程。
辞职() 退出(0) os._exit (0) sys.exit (0) Os.kill (os.getppid(), 9) -其中os.getppid()是父进程的pid
最后一个进程杀死了主进程和它自己,但其余进程仍然存活。
解决方案
我不得不通过外部命令杀死它,最后使用pkill找到解决方案。
import os
# This can be called even in process worker and will kill
# whole application included correlated processes as well
os.system(f"pkill -f {os.path.basename(__file__)}")
推荐文章
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录
- 我如何告诉matplotlib我已经完成了一个情节?
- 如何在Python中记录源文件名称和行号