我正在编写一个从 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/