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

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

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


当前回答

为什么要使用python呢?您可能会忘记删除它并将其签入存储库。只需运行python命令&&和另一个命令来执行警报。

python myscript.py && 
    notify-send 'Alert' 'Your task is complete' && 
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga

或者将一个函数放到.bashrc中。这里我用的是python但是你可以重写" python "

function apython() {
    /usr/bin/python $*
    notify-send 'Alert' "python $* is complete"
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
}

其他回答

这个似乎在Windows和Linux上都可以运行*(从这个问题来看):

def beep():
    print("\a")

beep()

在Windows中,可以在末尾放置:

import winsound
winsound.Beep(500, 1000)

where 500 is the frequency in Herz
      1000 is the duration in miliseconds

要在Linux上工作,你可能需要做以下事情(来自QO的评论):

在终端中,输入'cd /etc/modprobe。然后输入gksudo gedit blacklist.conf 注释一行说“黑名单pcspkr”,然后重新启动 还要检查终端首选项是否选中了“终端铃声”。

在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

在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')

我创建了一个python模块,在代码执行后提醒Telegram应用程序上的开发人员。这可能比发出警报声音更有帮助。

Pypi链接: https://pypi.org/project/devreminder/

Github链接: https://github.com/cagataygulten/devreminder

例子:

In [1]>>
    from devreminder import DevReminder
    import time

In [2]>>
    remind = DevReminder(1932126911,False,0)

In [3]>>
    remind.me("Example")
    time.sleep(6)

输出:

请按照README文件了解更多信息。