停止无限循环重复调用 os.system

Yon*_*Noh 5 python loops os.system try-catch python-3.x

谢谢大家看到我的帖子。

首先,以下是我的代码:

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)
"""
Run Code Online (Sandbox Code Playgroud)

我的问题是Ctrl + C 不起作用!

我尝试改变try块的位置,并制作信号(SIGINT)捕捉功能。

但那些也不起作用。

我看过/sf/answers/583464871//sf/answers/2304614931/和其他几个关于这个问题的答案。

我使用的是 MAC OS(10.12.3) 和 python 3.5.2。

far*_*sil 5

这是预期的行为,就像os.system()C 函数的薄包装一样system()如手册页中所述,父进程在执行命令期间忽略SIGINT。为了退出循环,您必须手动检查子进程的退出代码(这也在手册页中提到):

import os
import signal

while True:
    code = os.system('sleep 1000')
    if code == signal.SIGINT:
        print('Awakened')
        break
Run Code Online (Sandbox Code Playgroud)

然而,实现相同结果的首选(并且更Pythonic)方法是使用模块subprocess

import subprocess

while True:
    try:
        subprocess.run(('sleep', '1000'))
    except KeyboardInterrupt:
        print('Awakened')
        break
Run Code Online (Sandbox Code Playgroud)

您的代码将如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

作为补充说明,subprocess.run()仅适用于 Python 3.5+。您可以在旧版本的 Python 中使用它subprocess.call() 来实现相同的效果。