문제

출력에 트레이스 백 덤프없이 파이썬에서 나가는 방법을 알고 싶습니다.

여전히 오류 코드를 반환 할 수 있기를 원하지만 Traceback 로그를 표시하고 싶지 않습니다.

사용하여 종료 할 수 있기를 원합니다 exit(number) 추적이 없지만 예외 (출구가 아닌)의 경우 나는 흔적을 원합니다.

도움이 되었습니까?

해결책

당신은 아마도 예외를 만나고있을 것입니다.이 때문에 (추적으로) 프로그램이 종료되고 있습니다. 그러므로 가장 먼저해야 할 일은 깨끗하게 빠져 나가기 전에 그 예외를 포착하는 것입니다.

당신의 이와 같은 것을 시도하십시오 main 루틴:

import sys, traceback

def main():
    try:
        do main program stuff here
        ....
    except KeyboardInterrupt:
        print "Shutdown requested...exiting"
    except Exception:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)

if __name__ == "__main__":
    main()

다른 팁

아마도 당신은 모든 예외를 잡으려고 노력하고 있으며 이것은 SystemExit 예외가 제기되었습니다 sys.exit()?

import sys

try:
    sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
    sys.exit(e)
except:
    # Cleanup and reraise. This will print a backtrace.
    # (Insert your cleanup code here.)
    raise

일반적으로 사용합니다 except: 의 이름을 짓지 않으면 예외는 나쁜 생각입니다. 당신은 당신이 잡고 싶지 않은 모든 종류의 물건을 잡을 것입니다 - SystemExit - 또한 자신의 프로그래밍 오류를 숨길 수도 있습니다. 내 예제는 청소 측면에서 무언가를하지 않는 한 어리석은 일입니다. 당신은 그것을 대체 할 수 있습니다 :

import sys
sys.exit(1) # Or something that calls sys.exit().

모금하지 않고 종료 해야하는 경우 SystemExit:

import os
os._exit(1)

나는 이것을합니다. fork(). Forked 프로세스가 제기되면 UnitTest가 발생합니다 SystemExit. 이것은 확실히 코너 케이스입니다!

import sys
sys.exit(1)

같은 것 import sys; sys.exit(0) ?

다음 코드는 예외를 제기하지 않으며 추적없이 종료됩니다.

import os
os._exit(1)

이 질문과 관련 답변을 참조하십시오 자세한 사항은. 다른 모든 답변이 왜 이처럼 복잡한 지 놀랐습니다.

sys.exit ()를 사용하지 않고 프로그램이 깨끗하게 완료 될 수 있도록 예외를 올리거나 처리하는 것이 훨씬 좋습니다. Traceback을 끄고 싶다면 간단히 사용하십시오.

sys.trackbacklimit=0

스크립트 맨 위에 설정하여 모든 트레이스 백 출력을 스쿼시 할 수 있지만 예를 들어 출력이 깨끗해지기를 원하는 "알려진 오류"와 같이 더 드물게 사용하는 것이 좋습니다.

import sys
from subprocess import *

try:
  check_call([ 'uptime', '--help' ])
except CalledProcessError:
  sys.tracebacklimit=0
  print "Process failed"
  raise

print "This message should never follow an error."

호출 프로세서러가 잡히면 출력이 다음과 같습니다.

[me@test01 dev]$ ./foo.py
usage: uptime [-V]
    -V    display version
Process failed
subprocess.CalledProcessError: Command '['uptime', '--help']' returned non-zero exit status 1

다른 오류가 발생하면 여전히 전체 트레이스 백 출력이 발생합니다.

내장 된 Python 함수 quit ()를 사용하십시오. 도서관을 가져올 필요가 없습니다. 파이썬 3.4를 사용하고 있습니다

나는 이런 식으로 할 것이다 :

import sys

def do_my_stuff():
    pass

if __name__ == "__main__":
    try:
        do_my_stuff()
    except SystemExit, e:
        print(e)

는 어때

import sys
....
....
....
sys.exit("I am getting the heck out of here!")

추적이없고 어떻게 든 더 명백합니다.

# Pygame Example  

import pygame, sys  
from pygame.locals import *

pygame.init()  
DISPLAYSURF = pygame.display.set_mode((400, 300))  
pygame.display.set_caption('IBM Emulator')

BLACK = (0, 0, 0)  
GREEN = (0, 255, 0)

fontObj = pygame.font.Font('freesansbold.ttf', 32)  
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)  
textRectObj = textSurfaceObj.get_rect()  
textRectObj = (10, 10)

try:  
    while True: # main loop  
        DISPLAYSURF.fill(BLACK)  
        DISPLAYSURF.blit(textSurfaceObj, textRectObj)  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
        pygame.display.update()  
except SystemExit:  
    pass
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top