python链子进程管道将不一致的结果转储到文件

时间:2017-05-17 13:41:35

标签: python subprocess

我有一系列管道,其中一个管道输出到下一个管道的输入。第一个管道从字符串变量中获取数据。它们中的每一个都对输入执行操作。最后一个管道应该将结果转储到文件中。我的问题是转储到文件的结果不一致。

这里predstr是一个大字符串,max_pred确定要创建的子进程数。

def _bio2se(predstr, pred_base, prefix, max_pred):
    dump_file = '%s/prediction%s_preds' % (pred_base, prefix)
    _cmd = 'col-format.pl -%s -i bio -o se'
    start = sp.Popen((_cmd % ('1')).split(), stdin=sp.PIPE, stdout=sp.PIPE)

    p = []
    p.append(start)
    for i in range(1, max_pred-1):
        p.append(sp.Popen((_cmd % str(i+1)).split(), stdin=p[i-1].stdout, stdout=sp.PIPE))

    if os.path.exists(dump_file):
        os.remove(dump_file)

    with open(dump_file, 'w') as dumpf: 
        sp.Popen((_cmd % str(max_pred)).split(), stdin=p[-1].stdout, stdout=dumpf)
        start.communicate(input=predstr.encode())

编辑: 这可行,但它不是预期的解决方案,因为我不想写入文件并再次阅读。

def _bio2se_temp_file(predstr, pred_base, prefix, max_pred):
    dump_file = '%s/prediction%s_preds' % (pred_base, prefix)
    _cmd = 'col-format.pl -%s -i bio -o se'

    with tempfile.TemporaryFile() as f:
        f.write(predstr.encode())
        f.seek(0)
        start = sp.Popen('cat'.split(), stdin=f, stdout=sp.PIPE)

    p = []
    p.append(start)
    for i in range(0, max_pred-1):
        p.append(sp.Popen((_cmd % str(i+1)).split(), stdin=p[i].stdout, stdout=sp.PIPE))

    if os.path.exists(dump_file):
        os.remove(dump_file)

    with open(dump_file, 'w') as dumpf: 
        end = sp.Popen((_cmd % str(max_pred)).split(), stdin=p[-1].stdout, stdout=dumpf)

0 个答案:

没有答案