我的代码需要很长时间才能运行,我不想一直盯着它,但想知道它什么时候完成。

我怎样才能使(Python)代码在完成时发出“警报”?我正在考虑让它在代码结束时播放一个.wav文件……

这个想法可行吗? 如果是,我该怎么做呢?


当前回答

它可以通过如下代码来完成:

import time
time.sleep(10)   #Set the time
for x in range(60):  
    time.sleep(1)
    print('\a')

其他回答

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

在Windows上

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz
winsound.Beep(freq, duration)

其中,freq是以赫兹为单位的频率,持续时间以毫秒为单位。

Linux和Mac

import os
duration = 1  # seconds
freq = 440  # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))

为了使用这个示例,您必须安装sox。

在Debian / Ubuntu / Linux Mint上,在你的终端上运行这个:

sudo apt install sox

在Mac上,在你的终端上运行这个(使用macports):

sudo port install sox

在Mac上的演讲

import os
os.system('say "your program has finished"')

关于Linux的演讲

import os
os.system('spd-say "your program has finished"')

你需要在Ubuntu中安装speech-dispatcher包(或者在其他发行版中安装相应的包):

sudo apt install speech-dispatcher

我假设你想要标准的系统钟,不想关心频率和持续时间等,你只想要标准的窗户钟。

import winsound
winsound.MessageBeep()

在OS X Yosemite(10.10.1)上,Kuchi的答案对我不起作用。我确实找到了afplay命令(在这里),您可以从Python调用它。无论终端可听铃声是否启用,并且没有第三方库,都可以正常工作。

import os
os.system('afplay /System/Library/Sounds/Sosumi.aiff')

它可以通过如下代码来完成:

import time
time.sleep(10)   #Set the time
for x in range(60):  
    time.sleep(1)
    print('\a')