etc./StackOverFlow

스크립트를 종료하는 방법?

청렴결백한 만능 재주꾼 2023. 5. 4. 22:15
반응형

질문자 :Teifion


스크립트를 일찍 종료하는 PHP의 die()

파이썬에서 어떻게 할 수 있습니까?



import sys sys.exit()

sys 모듈 설명서의 세부 정보:

sys. exit ([ arg ])

파이썬을 종료합니다. SystemExit 예외를 발생시켜 구현 try 문의 finally 절에 지정된 정리 작업이 적용되며 외부 수준에서 종료 시도를 가로챌 수 있습니다.

선택적 인수 arg 는 종료 상태를 제공하는 정수(기본값은 0)이거나 다른 유형의 객체일 수 있습니다. 정수인 경우 0은 "성공적인 종료"로 간주되고 0이 아닌 값은 쉘 등에 의해 "비정상 종료"로 간주됩니다. 대부분의 시스템은 0-127 범위에 있어야 하며 그렇지 않으면 정의되지 않은 결과를 생성합니다. 일부 시스템에는 특정 종료 코드에 특정 의미를 할당하는 규칙이 있지만 일반적으로 개발되지 않았습니다. Unix 프로그램은 일반적으로 명령줄 구문 오류에 대해 2를 사용하고 다른 모든 종류의 오류에 대해 1을 사용합니다. 다른 유형의 객체가 전달되면 None은 0을 전달하는 것과 동일하고 다른 객체는stderr 인쇄되고 종료 코드는 1이 됩니다. 특히 sys.exit("some error message") 는 오류가 발생하면 프로그램을 종료합니다.

exit() 궁극적으로 "only" 예외를 발생시키므로 메인 스레드에서 호출될 때만 프로세스를 종료하고 예외는 가로채지 않습니다.

이것은 종료하는 '좋은' 방법입니다. 아래의 @ glyphtwistedmatrix 는 '하드 종료'를 os._exit(*errorcode*) 사용할 수 있다고 지적하지만 어느 정도 OS에 따라 다를 수 있습니다(예: 창에서는 오류 코드를 사용하지 않을 수 있음). 인터프리터가 프로세스가 종료되기 전에 정리를 수행하지 못하도록 하기 때문에 확실히 덜 친숙합니다. 다른 한편으로는 반면, 실행중인 모든 스레드를 포함하여 전체 프로세스를 종료하지 sys.exit() (가 문서에서 말하는 것처럼) 만 다른 스레드가 실행되지와 함께, 메인 쓰레드에서 호출하면 종료됩니다.


pjz

Python 스크립트를 조기에 종료하는 간단한 방법은 내장 quit() 함수를 사용하는 것입니다. 라이브러리를 가져올 필요가 없으며 효율적이고 간단합니다.

예시:

 #do stuff if this == that: quit()

j.m.g.r

또 다른 방법은 다음과 같습니다.

 raise SystemExit

Vhaerun

exit() 사용할 수도 있습니다.

마음에 계속 sys.exit() , exit() , quit()os._exit(0) 파이썬 인터프리터를 죽일. execfile() 의해 다른 스크립트에서 호출된 스크립트에 나타나면 두 스크립트의 실행을 모두 중지합니다.

이를 방지하려면 " execfile로 호출된 스크립트 실행 중지 "를 참조하십시오.


Space cowboy

sys.exit 가 다른 코드에 더 "친숙하기" 때문에 선호해야 하지만 실제로 하는 일은 예외를 발생시키는 것뿐입니다.

SystemExit catch하는 예외 처리기 내부에 있을 수 있다고 os._exit 하는 경우 C 수준에서 즉시 종료되고 어떠한 작업도 수행하지 않는 또 다른 함수인 os._exit가 있습니다. 통역사의 정상적인 분해; 예를 들어 "atexit" 모듈에 등록된 후크는 실행되지 않습니다.


Glyph

다중 스레드 응용 프로그램을 작성할 때 raise SystemExitsys.exit() 모두 발생시키면 실행 중인 스레드만 종료된다는 것을 방금 알았습니다. 반면에 os._exit() 는 전체 프로세스를 종료합니다. 이것은 " 왜 sys.exit()가 파이썬의 스레드 내부에서 호출될 때 종료되지 않습니까? "에서 논의되었습니다.

아래 예제에는 2개의 스레드가 있습니다. 케니와 카트맨. Cartman은 영원히 살아야 하지만 Kenny는 재귀적으로 호출되어 3초 후에 죽어야 합니다. (재귀 호출이 최선의 방법은 아니지만 다른 이유가 있었습니다)

Kenny가 죽을 때 Cartman도 죽기를 원한다면 Kenny는 os._exit . 그렇지 않으면 Kenny만 죽고 Cartman은 영원히 살 것입니다.

 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()

eaydin

from sys import exit exit()

매개변수로 종료 코드를 전달할 수 있으며 이는 OS로 반환됩니다. 기본값은 0입니다.


cleg

나는 완전히 초보자이지만 확실히 이것은 더 깨끗하고 제어됩니다.

 def main(): try: Answer = 1/0 print Answer except: print 'Program terminated' return print 'You wont see this' if __name__ == '__main__': main()

...

프로그램 종료

~보다

 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()

...

프로그램 종료 추적(가장 최근 호출 마지막): main() 파일 "Z:\Directory\testdieprogram.py", 줄 12, main sys.exit( ) 시스템 종료

편집하다

요점은 "I've STOPPED!!!!" 보다는 프로그램이 순조롭고 평화롭게 끝난다는 것입니다.


Floggedhorse

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!")

David C.

내 2센트.

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.')

복잡성에 따라 때때로 예외 섹션 등에서도 위의 설명을 반복해야 합니다.

 if immediateExit: sys.exit('CSV file corrupted 1.5.')

사용자 정의 메시지는 개인적인 디버깅을 위한 것이며 숫자는 스크립트가 실제로 종료되는 위치를 확인하기 위한 동일한 목적을 위한 것입니다.

 'CSV file corrupted 1.5.'

제 경우에는 소프트웨어가 손상되었음을 감지하면 소프트웨어가 건드리지 않기를 바라는 CSV 파일을 처리하고 있습니다. 따라서 나에게는 가능한 손상을 감지한 직후 전체 Python 스크립트를 종료하는 것이 매우 중요합니다.

그리고 내가 관리하는 모든 루프에서 점진적인 sys.exit-ing을 수행합니다.

전체 코드: (내부 작업을 위한 독점 코드이므로 일부 변경이 필요함):

 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.')

Matthew

출처 : http:www.stackoverflow.com/questions/73663/how-to-terminate-a-script

반응형