简体   繁体   English

终止由子进程执行的命令

[英]terminate comand executing by subprocess

I have a python script which listens to specific stream and records it like this: 我有一个python脚本,它监听特定的流并像这样记录它:

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

Also it checks tcp connection on port 7777 (when stream is live it connects to this port on my pc) I want to terminate subprocess command every time connection on port 7777 closes. 它还检查端口7777上的tcp连接(当流是活动时它连接到我的电脑上的这个端口)我希望每次端口7777上的连接关闭时终止子进程命令。 How can I do this? 我怎样才能做到这一点?

subprocess.call() is a blocking call - it waits for the subprocess to finish. subprocess.call()是一个阻塞调用 - 它等待子进程完成。

You may want to use subprocess.Popen() instead, which returns a Popen object that you can interact with and terminate using Popen.terminate() . 您可能需要使用subprocess.Popen()代替,它返回一个POPEN对象 ,你可以交互使用终止Popen.terminate()

See the documentation here . 请参阅此处文档

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)

Note : I have no clue what "socket" is but i'm assuming just a regular socket of sorts. 注意 :我不知道“套接字”是什么,但我假设只是一个常规套接字。
I'd like to point out that i'm by no means a perfect programmer but this would give you an idea of what you would need to do altho not perfect this would work :) 我想指出,我绝不是一个完美的程序员,但这会让你知道你需要做什么,尽管不完美这会工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM