【问题标题】:how to write a command with given condition in subprocess如何在子进程中编写具有给定条件的命令
【发布时间】:2020-09-10 11:32:30
【问题描述】:

我很难弄清楚如何在子进程中编写此命令。

在我运行的终端中:

ffprobe -i test.avi -show_format -v quiet | sed -n 's/duration=//p' | xargs printf %.0f

它运行良好。 现在在 python 3 中,我想在我的代码中运行它,它给了我一个错误。 我试过了

subprocess.call(['ffprobe', '-i', 'test.avi' ,'-show_format', '-v' ,'quiet' ,'|', 'sed' ,'-n' ,'s/duration=//p', '|' ,'xargs printf %.0f'])

subprocess.run(['ffprobe', '-i', 'test.avi' ,'-show_format', '-v' ,'quiet' ,'|', 'sed' ,'-n' ,'s/duration=//p', '|' ,'xargs printf %.0f']) 但没有一个有效。

【问题讨论】:

  • 分享错误信息。这将有助于确定问题。

标签: python-3.x subprocess ffprobe


【解决方案1】:

在终端中,| 用于将一个程序的输出通过管道传输到另一个程序的输入。

您的命令意味着以下流程:

ffmpeg => sed => xargs(和xargs 对其输入的每一行分别运行printf

Python 可以轻松接管sedxargs 的工作。

你的程序可能变成:

import subprocess
import re

# subprocess.run() is usually a better choice
completed = subprocess.run(
    [
        'ffprobe',
        '-i', 'test.avi', '-show_format', '-v', 'quiet',
    ],
    capture_output=True,  # output is stored in completed.stdout
    check=True,  # raise error if exit code is non-zero
    encoding='utf-8',  # completed.stdout is decoded to a str instead of a bytes
)

# regex is used to find the duration
for match in re.finditer(r'duration=(.*)$', completed.stdout):
    duration = float(match.group(1).strip())
    print(f'{duration:.0f}')  # f-string is used to do formatting

如果您想在 Python 中的命令之间进行管道连接,请参阅 How to use `subprocess` command with pipes

虽然子进程函数中有shell=True 参数,但它有security consideration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2023-01-30
    • 2021-11-20
    • 2011-10-20
    • 2019-05-25
    相关资源
    最近更新 更多