2013-08-09 2 views
1

여기 테스트 사례입니다. 내가 출력이 "취소"할 수 있도록 CTRL + C-raw_input 중에 KeyboardInterrupt를 잡을 수없는 이유는 무엇입니까?

NameError: name 'targ' is not defined 

내 의도가 누르면 다음과 같이

try: 
    targ = raw_input("Please enter target: ") 
except KeyboardInterrupt: 
    print "Cancelled" 
print targ 

내 출력됩니다. raw_input 동안 KeyboardInterrupt를 잡으려고 할 때 이것이 일어나는 이유는 무엇입니까?

감사합니다.

답변

3

위의 코드에서 예외가 발생하면 targ가 정의되지 않습니다. 예외가 발생하지 않은 경우에만 인쇄해야합니다.

try: 
    targ = raw_input("Please enter target: ") 
    print targ 
except KeyboardInterrupt: 
    print "Cancelled" 
2

KeyboardInterrupt이 발생하면 변수 targ이 초기화되지 않기 때문에 오류가 발생합니다. 당신은 예외가 발생하지 않은 경우 try 성명을 인쇄하여, targ를 인쇄하려면 코드를 변경 할 수

try: 
    targ = raw_input("Please enter target: ") 
except KeyboardInterrupt: 
    print "Cancelled" 


Please enter target: abc 

>>> targ 
'abc' 

가 발생하지 않습니다,

try: 
    targ = raw_input("Please enter target: ") 
except KeyboardInterrupt: 
    print "Cancelled" 

Please enter target: 
Cancelled 

>>> targ 

Traceback (most recent call last): 
    File "<pyshell#19>", line 1, in <module> 
    targ 
NameError: name 'targ' is not defined 

은 다음 데모를 참조하십시오.

try: 
    targ = raw_input("Please enter target: ") 
    print targ 
except KeyboardInterrupt: 
    print "Cancelled" 


Please enter target: abc 
abc 

try: 
    targ = raw_input("Please enter target: ") 
    print targ 
except KeyboardInterrupt: 
    print "Cancelled" 


Please enter target: 
Cancelled 
관련 문제