【问题标题】:asyncio call works in cmd but not in pythonasyncio 调用在 cmd 中有效,但在 python 中无效
【发布时间】:2017-08-15 21:41:58
【问题描述】:

我正在使用 sox 检索音频文件信息。有 2 个 windows cmd 命令可以正确返回信息:

C:\Users\Me> "path\to\sox.exe" "--i" "path\to\audiofile.wav"

C:\Users\Me> "path\to\sox.exe" "path\to\audiofile.wav" "-n" "stat" 

我正在使用 asyncio 脚本来运行这两个命令并收集数据进行处理。我使用下面的代码:

async def async_subprocess_command(*args):
    # Create subprocess
    process = await asyncio.create_subprocess_exec(
        *args,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE)
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()

    # Return stdout
    return stdout.decode().strip()

data1 = await async_subprocess_command(soxExecutable, "--i", audiofilepath)
data2 = await async_subprocess_command(soxExecutable, audiofilepath,"-n", "stat")

由于两个 cmd 命令都按预期运行,我很困惑 python 脚本中的 data2 总是空白。 Data1 符合预期(使用来自 sox 的数据)。

谁能帮我理解为什么?

【问题讨论】:

  • 第二个命令似乎写到stderr
  • 这是个好主意——我没想到。我还必须向 asyncio.create_subprocess_exec 添加一个 stderr=asyncio.subprocess.PIPE 参数,现在我可以看到它以 sterr 值返回。非常感谢文森特!

标签: python-3.x subprocess python-asyncio sox


【解决方案1】:

由于某种原因,第二个命令通过 sterr 返回其结果。我将附加参数添加到 asyncio.create_subprocess_exec 函数以将 sterr 连接到 asyncio.subprocess.PIPE。

   async def async_subprocess_command(*args):
        # Create subprocess
        process = await asyncio.create_subprocess_exec(
            *args,
            # stdout must a pipe to be accessible as process.stdout
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # Wait for the subprocess to finish
        stdout, stderr = await process.communicate()

        # Return stdout and sterr
        return stdout.decode().strip(),sterr.decode().strip()

    data1a, data1b = await async_subprocess_command(soxExecutable, "--i", audiofilepath)
    data2a, data2b = await async_subprocess_command(soxExecutable, audiofilepath,"-n", "stat")

【讨论】:

    猜你喜欢
    • 2012-02-13
    • 2020-06-15
    • 2021-02-26
    • 1970-01-01
    • 2019-01-19
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多