3

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

我曾经用以下方式调用 youtube-dl subprocess

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 进行打印。

你能帮助我吗?

4

2 回答 2

4

特别是对于 youtube-dl,您可以设置一个记录器对象,就像在文档中的高级示例中一样:

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])
于 2015-02-03T12:25:49.447 回答
1

您可以尝试将 sys.stdout 重定向到您自己的输出流,
请参阅:https ://stackoverflow.com/a/1218951/2134702


引用链接的答案:

from cStringIO import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

如果你想在重定向期间输出到标准输出,而不是打印使用 old_stdout.write()

于 2015-02-03T11:16:24.790 回答