【问题标题】:Stop opening VLC in python停止在 python 中打开 VLC
【发布时间】:2016-01-04 15:58:56
【问题描述】:

我写了一个小代码,它扫描空中的 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 运行一次代码然后停止?

已经非常感谢了!

【问题讨论】:

  • 为什么while True:
  • 如果你只想运行一次,不要使用while循环
  • 那么循环在这段代码中的什么位置?我将这段代码复制粘贴在一起,我知道,这从来都不聪明,但我是新手

标签: python command


【解决方案1】:

两件事:

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

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 我想在脚本中添加一个“终止”代码行。你知道吗?
    猜你喜欢
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多