Skip to main content
 首页 » 编程设计

python之子进程无法捕获标准输出

2025年05月04日15telwanggs

我正在尝试使用 fasta 文件输入和与 MuscleCommandline 对齐生成树

import sys,os, subprocess 
from Bio import AlignIO 
from Bio.Align.Applications import MuscleCommandline 
cline = MuscleCommandline(input="c:\Python26\opuntia.fasta") 
child= subprocess.Popen(str(cline), 
                         stdout = subprocess.PIPE, 
                         stderr=subprocess.PIPE, 
                        shell=(sys.platform!="win32")) 
align=AlignIO.read(child.stdout,"fasta") 
outfile=open('c:\Python26\opuntia.phy','w') 
AlignIO.write([align],outfile,'phylip') 
outfile.close() 

我总是遇到这些问题

Traceback (most recent call last): 
  File "<string>", line 244, in run_nodebug 
  File "C:\Python26\muscleIO.py", line 11, in <module> 
    align=AlignIO.read(child.stdout,"fasta") 
  File "C:\Python26\Lib\site-packages\Bio\AlignIO\__init__.py", line 423, in read 
    raise ValueError("No records found in handle") 
ValueError: No records found in handle 

请您参考如下方法:

这里有一些问题:

  1. 在子进程调用之后您需要一个 child.wait(),这样您的代码将等待外部程序完成运行。

  2. Muscle 实际上并没有写入 stdout,尽管帮助文档说它写入了,至少对于我这里的 v3.6 是这样。我相信最新的是 v3.8,所以这可能会得到修复。

Biopython 告诉您传递给它的标准输出是空的,这就是您看到的错误。尝试直接运行命令行:

muscle -in opuntia.fasta

看看您是否看到 FASTA 输出。这是修复等待问题并使用中间输出文件的版本:

 
import sys,os, subprocess 
from Bio import AlignIO 
from Bio.Align.Applications import MuscleCommandline 
out_file = "opuntia.aln" 
cline = MuscleCommandline(input="opuntia.fasta", out=out_file) 
child= subprocess.Popen(str(cline), 
                         stdout = subprocess.PIPE, 
                         stderr=subprocess.PIPE, 
                        shell=(sys.platform!="win32")) 
child.wait() 
with open(out_file) as align_handle: 
    align=AlignIO.read(align_handle,"fasta") 
outfile=open('opuntia.phy','w') 
AlignIO.write([align],outfile,'phylip') 
outfile.close() 
os.remove(out_file)