停止在python中打开VLC

时间:2016-01-04 15:58:56

标签: python command

我写了一个小代码,它扫描空中的wifi信号,并根据播放一个或另一个音频文件的数量。

import time
import subprocess
import os

while True:
    output = subprocess.Popen("airport en1 -s", shell=True, stdout=subprocess.PIPE).stdout.read()
    lines = output.split('\n')
    n = len(lines)
    if n < 10:
        print os.path.exists('/Users/shirin/Desktop/wifi/1.mp3') 
        p = subprocess.Popen(['/Applications/VLC.app/Contents/MacOS/VLC','/Users/shirin/Desktop/wifi/1.mp3'])
    elif n > 10:
        print os.path.exists('/Users/shirin/Desktop/wifi/1.mp3') 
        p = subprocess.Popen(['/Applications/VLC.app/Contents/MacOS/VLC','/Users/shirin/Desktop/wifi/1.mp3'])

现在我的问题是,当我通过终端运行文件时,它会一遍又一遍地运行代码,我不知道如何阻止它。当我关闭终端时它也不会停止。 所以我的问题: 我怎么能告诉python一次运行代码然后停止?

已经非常感谢!

2 个答案:

答案 0 :(得分:1)

两件事:

  • 你有while True:并没有条件来打破循环,在重现音频文件后插入break以便循环停止。
  • 即使您关闭程序,VLC也会一直运行,直到您手动停止它为止。这是因为您只是调用外部命令。如果你想从python重现音频,你可以使用另一个库,如pygame

答案 1 :(得分:-1)

如果要终止申请,可以致电p.terminate()

如果您的应用程序没有响应,您也可以致电p.kill()

现在,假设您要停止应用程序并停止VLC。

在代码中使用except KeyboardInterrupt:,并在停止脚本时调用p.terminate()

while True:
    try:
    ... #code goes here.
    except KeyboardInterrupt:
        p.terminate()