如何使子进程对象将输出保存到临时文件,然后从临时文件中获取值?

How to make a subprocess object save output to a temporary file and then obtain values from temporary file?

我目前在 Python 代码中使用基于 Unix 的可执行文件来分析一些 DNA 序列。在 运行 分析之后,这个特定的可执行文件将输出写入一个文件,然后我的代码读取该文件并从中获取相关值。

由于除了产生一些值外不需要该文件,因此我决定将其设为临时文件,在从中获取必要信息后将被删除。然而,我为实现这一目标而设置代码的努力被证明是徒劳的。

import subprocess as sb
import tempfile

def calculate_complex_mfe(DNA_seq):
    complex_seq= str(DNA_seq)
    with tempfile.NamedTemporaryFile as mfefile:
        p= sb.Popen(['/Users/john/Documents/Biology/nupack3.0.6/bin/mfe', '-T', '41'], stdin=sb.PIPE, stdout=sb.PIPE, env=my_env)
        strb = (mfefile+'\n'+ complex_seq + '\n').encode('utf-8')
        data = p.communicate(input=strb)
        mfe= float(open(mfefile+'.mfe').readlines()[14])
    return mfe

我应该注意到,strb 变量的设置是为了将可执行文件所需的格式与 运行 相匹配。同样对于它的价值,我使用的正常运行的原始代码发布在下面。

def calculate_complex_mfe(DNA_seq):
    complex_seq= str(DNA_seq)
    filename= "mfe-file"
    p= sb.Popen(['/Users/john/Documents/Biology/nupack3.0.6/bin/mfe', '-T', '41'], stdin=sb.PIPE, stdout=sb.PIPE, env=my_env)
    strb = (filename+'\n'+ complex_seq + '\n').encode('utf-8')
    data = p.communicate(input=strb)
    mfe= float(open(filename+'.mfe').readlines()[14])
    return mfe

谁能告诉我如何为可执行文件的输出创建一个临时文件,以便从中获取一些值?

来自文档:

NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True) Create and return a temporary file.

Returns an object with a file-like interface; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed unless the 'delete' argument is set to False.

您不需要要写入的文件句柄,您只需要创建一个临时文件名称,而不是打开一个临时文件。只需替换:

filename= "mfe-file"

来自

filename = tempfile.mktemp()

在你的第二个片段中为你生成一个临时文件名(完整路径)

完成后别忘了os.remove(filename)它。