【问题标题】:youtube-dl process hangs with RedirectStandardOutputyoutube-dl 进程因 RedirectStandardOutput 而挂起
【发布时间】:2021-10-08 04:07:45
【问题描述】:

尝试编写一个基本的 Powershell 脚本,该脚本将从 URL 中提取视频,并在需要时使用 FFmpeg 剪切它们。

我需要预先做的一件事是从网站上拉取下载选项,看看我是想使用-f best 还是-f bestvideo+bestaudio。所以我需要运行youtube-dl -F [url] 并返回输出,但我似乎不能不挂起:

param(
  [string]$url = "https://www.youtube.com/watch?v=njX2bu-_Vw4"
)

$YTDLinfo = New-Object System.Diagnostics.ProcessStartInfo
$YTDLinfo.FileName = "youtube-dl"
$YTDLinfo.RedirectStandardError = $false
$YTDLinfo.RedirectStandardOutput = $true
$YTDLinfo.UseShellExecute = $false
$YTDLinfo.Arguments = "-F $url"
$YTDL = New-Object System.Diagnostics.Process
$YTDL.StartInfo = $YTDLinfo
$YTDL.Start() | Out-Null
$YTDL.WaitForExit()

$YTDLStdOut = $YTDL.StandardOutput.ReadToEnd().split([Environment]::NewLine)

Write-Host $YTDLStdOut

如果我将 $YTDLinfo.RedirectStandardOutput 更改为 $false 它可以工作并将输出直接返回到控制台,但我需要在变量中输出。还值得一提的是,如果我运行上述但没有传递任何参数($YTDLinfo.Arguments = "")它也可以工作,即使$YTDLinfo.RedirectStandardOutput 设置为$true,并且只返回一些关于它如何需要一个 url 的 youtube-dl 术语.

解释起来有点混乱,但它只在重定向标准输出和提供-F [url] 时才会挂起。有什么想法吗?

【问题讨论】:

    标签: .net powershell powershell-7.0


    【解决方案1】:

    您的直接问题是您正在等待进程退出而没有确保您首先完全使用其重定向的 stdout 输出.

    也就是说,您的.WaitForExit() 调用可能会无限期等待,即如果进程创建了多个输出缓冲区的标准输出数据,这阻塞进程直到更多调用者读取数据。

    因此,请致电$YTDL.StandardOuput.ReadToEnd() 之前 $YTDL.WaitForExit()


    但是,值得退后一步

    为了从 PowerShell 执行 控制台应用程序(例如 youtube-dl同步,它们的 stdout 和 stderr 流连接到等效的PowerShell output streams直接调用它们,就像在任何 shell 中一样

    # Directly captures youtube-dl's stdout output as an *array of lines*.
    $YTDLStdOut = youtube-dl -F $url
    

    使用重定向2> 来捕获文件中的stderr输出。

    或者,使用2>&1 在变量中捕获stdout 和stderr merged,然后区分哪个输出行来自哪个流:-is [string] 暗示stdout -见this answer

    有关通过直接调用控制台程序捕获 stdout 和 stderr 的全面概述,请参阅 this answer

    具体而言,通常应避免使用以下技术调用控制台应用程序:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多