python - 如何在 Python 中通过管道传输 Python 进程的输出?

标签 python pipe piping youtube-dl

我正在编写一个从 YouTube 下载视频的程序,使用 youtube-dl .

我曾经使用 subprocess 调用 youtube-dl:

import subprocess

p = subprocess.Popen([command], \
    stdout=subprocess.PIPE, \
    stderr=subprocess.STDOUT, \
    universal_newlines = True)

然后,我会通过调用读取进程的输出:

for line in iter(p.stdout.readline, ""):
    hide_some_stuff_using_regex()
    show_some_stuff_using_regex()

不过,我更喜欢使用 youtube-dl 作为 Python 类。所以我现在这样做:

from youtube_dl import YoutubeDL as youtube_dl

options = {"restrictfilenames": True, \
           "progress_with_newline": True}

ydl = youtube_dl(options)
ydl.download([url])

代码有效,但我很难找到如何通过管道传输 youtube-dl 的输出。请注意,我想使用 youtube-dl 的部分输出进行实时打印,因此将 sys.stdout 重定向到自定义输出流将不起作用,因为我仍然需要 sys.stdout 进行打印。

你能帮帮我吗?

最佳答案

特别是对于 youtube-dl,你可以设置一个记录器对象,就像在 advanced example 中一样在文档中:

from youtube_dl import YoutubeDL


class MyLogger(object):
    def debug(self, msg):
        print('debug information: %r' % msg)

    def warning(self, msg):
        print('warning: %r' % msg)

    def error(self, msg):
        print('error: %r' % msg)


options = {
    "restrictfilenames": True,
    "progress_with_newline": True,
    "logger": MyLogger(),
}

url = 'http://www.youtube.com/watch?v=BaW_jenozKc'
with YoutubeDL(options) as ydl:
    ydl.download([url])

关于python - 如何在 Python 中通过管道传输 Python 进程的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28297338/

相关文章:

python - 尝试更新 libpython3.6-stdlib 导致覆盖错误

python - 将数字 ID 转换为简短的不同字母数字代码的算法

python - 获取ec2实例 block 设备的卷Id

Angular Uppercase/Lowercase Pipe - 为什么不直接使用 css?

grep - 使用 grep 管道错误消息

python - 如何从矩阵中找到线性独立的行

Python - 如何使用管道执行 shell 命令,但没有 'shell=True' ?

sql - 在swift中通过命令行重建SQL数据库

docker - 将文件通过管道传输到 docker run

c - 在 C 中实现管道时出现错误的文件描述符错误