等待外部程序完成写入文件

时间:2014-03-15 13:54:18

标签: python subprocess sox

我有一个调用外部程序的Python脚本(sox是准确的)。现在我必须用sox做几件事,但总是要等到一个文件完成写入,所以我可以在下一个命令中将它用作输入文件。

subprocess.wait()不起作用,因为sox的执行将完成,但文件不会写完。

这是我的代码:

import tempfile
import shlex

file_url = '/some/file.wav'
out_file = 'some/out.wav'
tmp_file = tempfile.NamedTemporaryFile()
pad_cmd = 'sox ' + file_url + ' ' + tmp_file.name + ' pad 0.0 3.0'
subprocess.call(shlex.split(pad_cmd))
trim_cmd = 'sox ' + tmp_file.name + ' -t wav ' + out_file + ' trim 0.0 3.0'

任何等待文件完成写入tmp_file.name而不使用等待一段固定时间的计时器的方法。或者sox中是否有内置方式将输出文件用作输入?特殊文件名-不适用于padtrim

2 个答案:

答案 0 :(得分:2)

如果sox works with stdin/stdout

#!/bin/sh
sox input.wav -t wav - pad 0.0 3.0 | sox -t wav - out.wav trim 0.0 3.0

然后你可以用Python编写它:

#!/usr/bin/env python
from subprocess import Popen, PIPE

pad = Popen(["sox", "input.wav", "-t", "wav", "-", "pad", "0.0", "3.0"],
            stdout=PIPE)
trim = Popen(['sox', '-t', 'wav', '-', 'out.wav', 'trim', '0.0', '3.0'],
             stdin=pad.stdout)
pad.stdout.close() # notify pad on write if trim dies prematurely
pipestatus = [p.wait() for p in [pad, trim]]

注意:如果您不使用不受信任的输入来构造命令,那么您可以将它们作为单行传递以便于阅读(在这种情况下,shell会创建管道):

#!/usr/bin/env python
from subprocess import check_call

cmd = "sox input.wav - -t wav pad 0.0 3.0 | sox - -t wav out.wav trim 0.0 3.0"
check_call(cmd, shell=True)

如果你不能写入/读取stdout / stdin,那么你可以尝试命名管道,以避免等待文件:

#!/bin/sh
mkfifo /tmp/sox.fifo
sox /tmp/sox.fifo -t wav out.wav trim 0.0 3.0 & # read from fifo
sox input.wav /tmp/sox.fifo pad 0.0 3.0         # write to fifo

或在Python中相同:

#!/usr/bin/env python
from subprocess import Popen, check_call

with named_pipe() as path:
    trim = Popen(["sox", path, '-t', 'wav', 'out.wav', 'trim', '0.0', '3.0'])
    check_call(["sox", "input.wav", path, "pad", "0.0", "3.0"]) # pad
rc = trim.wait()

其中named_pipe()定义为:

import os
from contextlib import contextmanager
from shutil     import rmtree
from tempfile   import mkdtemp

@contextmanager
def named_pipe():
    dirname = mkdtemp()
    try:
        path = os.path.join(dirname, 'named_pipe')
        os.mkfifo(path)
        yield path
    finally:
        rmtree(dirname)

答案 1 :(得分:1)

您可以等待文件,然后才能阅读:

handle = open(tmp_file.name)
from subprocess import select
select.select([handle], [], [])