私の投稿を見てくれてありがとう。
まず、私のコードは次のとおりです。
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)とPython3.5.2を使用しています。
これはos.system()
、C関数の薄いラッパーと同様に、予想される動作system()
です。マニュアルページに記載されているように、親プロセスはコマンドの実行中にSIGINTを無視します。ループを終了するには、子プロセスの終了コードを手動で確認する必要があります(これはmanページにも記載されています)。
import os
import signal
while True:
code = os.system('sleep 1000')
if code == signal.SIGINT:
print('Awakened')
break
ただし、同じ結果を達成するための推奨される(そしてよりPythonicな)方法は、subprocess
モジュールを使用することです。
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()
Python3.5以降でのみ使用できます。を使用subprocess.call()
して、古いバージョンのPythonで同じ効果を実現できます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加