我该如何在Python中将Python进程的输出导入?

3

我正在编写一个从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 是什么? - user1907906
很好,已更新。 - Exeleration-G
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])

很好。能够与开发者本人保持联系真是太棒了! - Exeleration-G
获取FFmpeg信息怎么样?我想抓取 frame= 1766 fps=157 q=-1.0 Lsize= 10152kB time=00:01:13.66 bitrate=1128.9kbits/s speed=6.54x 这一行。 - LukeSavefrogs

1
你可以尝试将sys.stdout重定向到自己的输出流
参见: https://dev59.com/8XM_5IYBdhLWcg3wzmnL#1218951


引用链接答案中的内容:

要引用链接中的答案:

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),而不是使用print,可以使用old_stdout.write()。


1
这应该是一条注释,而不是一个答案。 - user1907906
我考虑过这个问题,但是一旦我将sys.stdout重定向到输出流,我就不能再使用print了,对吧?print语句会被重定向到输出流而不会在屏幕上打印。这是一个问题,因为我想实时在屏幕上打印出youtube-dl输出的某些部分。 - Exeleration-G
@Exeleration-G,如果你保存stdout流(如链接答案中所示),你可以向其写入内容(而不是使用print命令),并且它将实时打印到主屏幕上。 - Eran
@Eran:当然可以!我没有想到可以使用 old_stdout.write() 这样的东西! - Exeleration-G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接