我写了一个小代码,它扫描空中的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一次运行代码然后停止?
已经非常感谢!
答案 0 :(得分:1)
两件事:
while True:
并没有条件来打破循环,在重现音频文件后插入break
以便循环停止。答案 1 :(得分:-1)
如果要终止申请,可以致电p.terminate()
。
如果您的应用程序没有响应,您也可以致电p.kill()
。
现在,假设您要停止应用程序并停止VLC。
在代码中使用except KeyboardInterrupt:
,并在停止脚本时调用p.terminate()
。
while True:
try:
... #code goes here.
except KeyboardInterrupt:
p.terminate()