如何将 Python 进程的输出传输到 Python 中?

How can I pipe a Python process' output in Python?

我正在编写一个从 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 class。所以我现在这样做:

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

你能帮帮我吗?

您可以尝试重定向 sys.stdout 到您自己的输出流
参见:


引用链接的答案:

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()

如果你想输出到stdout 在重定向期间,使用 old_stdout.write()

而不是打印

专门针对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])