【问题标题】:terminate comand executing by subprocess终止子进程的命令执行
【发布时间】:2014-03-25 20:33:40
【问题描述】:

我有一个 python 脚本,它监听特定的流并像这样记录它:

subprocess.call(['ffmpeg', '-y', '-i', 'udp://streamurl:streamport', '-acodec', 'copy', '-f', 'mp3', 'filename.mp3'])

它还检查端口 7777 上的 tcp 连接(当流处于活动状态时,它连接到我电脑上的此端口)我想在每次端口 7777 上的连接关闭时终止子进程命令。我该怎么做?

【问题讨论】:

    标签: python ffmpeg streaming subprocess


    【解决方案1】:

    subprocess.call() 是一个阻塞调用 - 它等待子进程完成。

    您可能想改用subprocess.Popen(),它会返回一个Popen object,您可以使用Popen.terminate()与之交互和终止。

    请参阅documentation here

    【讨论】:

      【解决方案2】:
      from subprocess import Popen, STDOUT, PIPE
      from time import sleep
      
      def connected(sock):
          try:
              sock.send(b'')
          except:
              return False
          return True
      
      handle = Popen(['ffmpeg', '-y', '-i', 'udp://streamurl:streamport', '-acodec', 'copy', '-f', 'mp3', 'filename.mp3'], shell=False, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
      
      output = ''
      while handle.poll() is None and connected(socket): # No exit code given, ergo command still running
          output += handle.stdout.readline()
          sleep(0.025)
      
      if not connected(socket):
          handle.terminate()
      
      output += handle.stdout.read()
      handle.stdout.close()
      handle.stdin.close()
      print(output)
      

      注意:我不知道“套接字”是什么,但我假设只是一个普通的套接字。
      我想指出,我绝不是一个完美的程序员,但这会让你知道你需要做什么,尽管这并不完美:)

      【讨论】:

      • 如果ffmpeg 生成足够的输出来填充管道缓冲区,或者如果它从标准输入读取,那么它可能会阻塞并且什么都不做。不要将stdout/stdin 设置为PIPE,除非您想从管道读取/写入。 None 也是单身人士。使用something is None 而不是something == None
      • @J.F.Sebastian 请详细说明None,因为你失去了我.. 在这种情况下使用is== 之间的实际区别是什么?
      • 只有NoneNone。可能有许多对象等于None(试试看:如果otherNone,则定义返回True__eq__(other) 方法。
      • @J.F.Sebastian Gotcha!实际上认为 Python 会以相同的方式处理 is== 对象的类型.. 猜不是:) 谢谢你澄清这一点!
      • 管道处理大错​​特错。 handle.stdout.read() 在读取 all 输出之前不会返回。我不确定sock.send(b'') 做了什么(它与问题无关。我只是放弃connected() 定义。
      猜你喜欢
      • 1970-01-01
      • 2019-03-18
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2021-09-08
      • 2014-02-12
      相关资源
      最近更新 更多