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

我正在编写一个程序,使用youtube-dl从YouTube下载视频.我曾经用子流程调用youtube-dl:import subprocessp = subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, univers...

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

我曾经用子流程调用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进程的输出?

基础教程推荐