【问题标题】:Subprocess unrecognized arguments but command works in terminal [duplicate]子进程无法识别的参数,但命令在终端中有效[重复]
【发布时间】:2020-07-25 00:03:36
【问题描述】:

我运行 DeepSpeech 命令将 wav 转换为文本,并希望将结果保存到文本文件中,如下所示:

deepspeech --model path/to/model --audio path/to/audio >> path/to/result.txt

它可以在终端中运行,但是如果我尝试像这样在 Python 中将其作为子进程运行:

subprocess.run(["deepspeech", "--model", "path/to/model", "--audio", "path/to/audio", ">>", "path/to/result.txt"])

我明白了:

usage: deepspeech [-h] --model MODEL [--lm [LM]] [--trie [TRIE]] --audio AUDIO
              [--beam_width BEAM_WIDTH] [--lm_alpha LM_ALPHA]
              [--lm_beta LM_BETA] [--version] [--extended] [--json]
deepspeech: error: unrecognized arguments: >> path/to/result.txt

有解决办法吗?

【问题讨论】:

    标签: python subprocess


    【解决方案1】:
    >> path/to/result.txt
    

    这不是deepspeech 的参数。这是一个称为“输出重定向”的 shell 功能。 deepspeech 显然不明白这一点。

    要在subprocess 中获得相同的行为,您可以使用stdout 选项:

    subprocess.run(["deepspeech", "--model", "path/to/model", "--audio", "path/to/audio"] , stdout=open("path/to/result.txt", 'a')])
    

    有关更多信息,请参阅Popen

    stdin、stdout 和 stderr 分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值为 PIPE、DEVNULL、现有文件描述符(正整数)、现有文件对象和无。 PIPE 表示应该创建一个通往子级的新管道。 DEVNULL 表示将使用特殊文件 os.devnull。默认设置为None,不会发生重定向;子文件句柄将从父文件继承。此外,stderr 可以是 STDOUT,这表明来自应用程序的 stderr 数据应该被捕获到与 stdout 相同的文件句柄中。

    【讨论】:

    • 别忘了关闭文件... ;-)
    • 很好,感谢您的详尽解释,这很有帮助!
    【解决方案2】:

    我认为你可以做到:

    with open("path/to/result.txt", mode="wb" as fd:
        subprocess.run(["deepspeech", "--model", "path/to/model", "--audio", "path/to/audio"], stdout=fd)
    

    或者捕获输出。

    阅读subprocess.run的文档。

    【讨论】:

    • 完全照做,效果很好。谢谢!
    • @Laurent LAPORTE:我试图运行这个命令with open("C:/Users/hp/Documents/result.txt", mode="wb") as fd: subprocess.run(["deepspeech", "--model", "--model C:/deepspeechwk/deepspeech-0.6.0-models/output_graph.pb --lm C:/deepspeechwk/deepspeech-0.6.0-models/lm.binary --trie C:/deepspeechwk/deepspeech-0.6.0-models/trie", "--audio", "C:/deepspeechwk/audio/8455-210777-0068.wav"], stdout=fd),但是生成的文件是空白的,但是当我从终端运行时,同样的工作你能告诉我是什么问题
    猜你喜欢
    • 2016-10-22
    • 2021-02-20
    • 2018-06-09
    • 1970-01-01
    • 2020-07-08
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多