python子流程管道链将不一致的结果转储到fi

2024-10-06 07:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这里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)

Tags: cmdbase管道stdinstdoutdumpstartsp