2016-01-04 31 views
-2

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

停止在python中打开VLC

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运行一次代码,然后停止?

已经非常感谢!

+0

为什么'while while True:'? – Trompa

+0

如果你只想运行一次,不要使用while循环 –

+0

这段代码在哪里坐循环呢?我将复制的代码粘贴在一起,这从来都不聪明,我知道,但我是一个newby – malina

回答

-1

如果您想终止您的应用程序,您可以致电p.terminate()

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

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

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

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

我想在脚本中添加一个“terminate”代码行。你知道这件事吗? – malina

1

两件事情:

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