2017-03-09 3 views
3

내 게시물을 확인해 주셔서 감사합니다.os.system을 반복적으로 호출하면서 무한 루프를 중지하십시오.

import os 

print("You can create your own message for alarm.") 
user_message = input(">> ") 

print("\n<< Sample alarm sound >>") 

for time in range(0, 3): 
    os.system('say ' + user_message) # this code makes sound. 

print("\nOkay, The alarm has been set.") 

""" 
##### My problem is here ##### 
##### THIS IS NOT STOPPED ##### 

while True: 
    try: 
     os.system('say ' + user_message) 
    except KeyboardInterrupt: 
     print("Alarm stopped") 
     exit(0) 
""" 

내 문제가 Ctrl + C가 작동하지 않는다는 것입니다 :

먼저, 다음은 내 코드입니다!

try 블록의 위치를 ​​변경하고 신호 (SIGINT) 잡기 기능을 시도했습니다.

그러나 이것도 작동하지 않습니다.

나는이 문제에 대해 https://stackoverflow.com/a/8335212/5247212, https://stackoverflow.com/a/32923070/5247212 및 기타 여러 답변을 보았습니다.

저는 MAC OS (10.12.3) 및 python 3.5.2를 사용하고 있습니다. os.system()은 C 함수 system()의 thin 래퍼로

+0

당신이 본 적이 [이 질문] (http://stackoverflow.com/questions/18047657/stop-python-in- terminal-on-mac)? – asongtoruin

+1

윈도우 7과 우분투 14.04에서 잘 작동하는 것으로 보입니다. (분명히 MACOS 특정 "명령"명령을 인쇄물로 대체해야했지만 요점은 ctrl-C가 올바르게 트랩되어 인쇄 된 알람을 인쇄하고 종료 함) – heroworkshop

답변

3

타기. man page에 나와 있듯이 부모 프로세스 은 명령 실행 중에 SIGINT를 무시합니다. 그러나

import os 
import signal 

while True: 
    code = os.system('sleep 1000') 
    if code == signal.SIGINT: 
     print('Awakened') 
     break 

의를 달성하기 위해 선호 (더 파이썬) 방법 : 루프를 종료하기 위해 수동으로 자식 프로세스의 종료 코드 (이 또한 사람의 페이지에서 언급)을 확인해야

귀하의 코드는 다음과 같이 뭔가 같을 것이다
import subprocess 

while True: 
    try: 
     subprocess.run(('sleep', '1000')) 
    except KeyboardInterrupt: 
     print('Awakened') 
     break 

가 :

추가 참고로
import subprocess 

print("You can create your own message for alarm.") 
user_message = input(">> ") 

print("\n<< Sample alarm sound >>") 

for time in range(0, 3): 
    subprocess.run(['say', user_message]) # this code makes sound. 

print("\nOkay, The alarm has been set.") 

while True: 
    try: 
     subprocess.run(['say', user_message]) 
    except KeyBoardInterrupt: 
     print("Alarm terminated") 
     exit(0) 

, subprocess.run()은 availa이 같은 결과는 subprocess 모듈을 사용하는 것입니다 파이썬 3.5 이상. 이전 버전의 Python에서는 subprocess.call()to achieve the same effect을 사용할 수 있습니다.

0

또한 "SystemExit없이"이는 예상되는 동작

except (KeyboardInterrupt, SystemExit): 
    print("Alarm stopped") 
+2

아니요 .. 너무 효과적이지 않습니다.이 코드를 사용해 보셨습니까? –

0

문제는 Ctrl + C가 os.system을 통해 호출하는 하위 프로세스에 의해 캡처 된 것으로 보입니다. 이 서브 프로세스는 대응하고, 아마도 그것이 무엇이든간에 종결함으로써 대응한다. 그렇다면 os.system()의 반환 값은 0이 아닙니다. 이를 사용하여 while 루프를 깨뜨릴 수 있습니다. 여기

이 ( sleep에 의해 say 대체) 나와 함께 작동하는 예입니다 :

import os 
import sys 

while True: 
    try: 
     if os.system('sleep 1 '): 
      raise KeyboardInterrupt 
    except KeyboardInterrupt: 
     print("Alarm stopped") 
     sys.exit(0)