TypeError:无法使用Python3.5隐式地将'bytes'对象转换为str

时间:2018-04-15 17:07:52

标签: python

我在以下代码中使用Python 3.5。

def raxml(DIR,cleaned,num_cores,seqtype):
        assert cleaned.endswith(".aln-cln"),\
                "raxml infile "+cleaned+" not ends with .aln-cln"
        assert seqtype == "aa" or seqtype == "dna","Input data type: dna or aa"
        assert len(read_fasta_file(DIR+cleaned)) >= 4,\
                "less than 4 sequences in "+DIR+cleaned
        clusterID = cleaned.split(".")[0]
        tree = DIR+clusterID+".raxml.tre"
        raw_tree = "RAxML_bestTree."+cleaned
        model = "PROTCATWAG" if seqtype == "aa" else "GTRCAT"
        if not os.path.exists(tree) and not os.path.exists(raw_tree):
                # raxml crashes if input file starts with . 
                infasta = cleaned if DIR == "./" else DIR+cleaned
                cmd = ["raxml","-T",str(num_cores),"-p","12345","-s",\
                       infasta,"-n",cleaned,"-m",model]
                print (" ".join(cmd))
                p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
                out = p.communicate()
                assert p.returncode == 0,"Error raxml"+out[0]
        try:
                os.rename(raw_tree,tree)
                os.remove("RAxML_info."+cleaned)
                os.remove("RAxML_log."+cleaned)
                os.remove("RAxML_parsimonyTree."+cleaned)
                os.remove("RAxML_result."+cleaned)
                os.remove(DIR+cleaned+".reduced")
        except: pass # no need to worry about extra intermediate files
        return tree

它运行并返回以下代码:

"raxml_wrapper.py", line 30, in raxml
        assert p.returncode == 0,"Error raxml"+out[0]
TypeError: Can't convert 'bytes' object to str implicitly

最初,我尝试了以下内容:

 p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
 p = p.decode('utf-8')
 out = p.communicate()
 assert p.returncode == 0,"Error raxml"+out[0]

根本没有解决问题。我看过类似的问题,但我无法想出解决方案。我很感激你的帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

pPopen个对象,没有.decode(...)成员。

您需要实际解码输出

p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, _ = p.communicate()
out = out.decode('utf-8')
assert p.returncode == 0, 'Error raxml' + out[0]

也就是说,可以改进此代码以使用subprocess.check_output

# does roughly the same thing, you'll get `subprocess.CalledProcessError` instead of `AssertionError`
out = subprocess.check_output(cmd).decode('UTF-8')

或者如果你碰巧使用的是python3.6 +

out = subprocess.check_output(cmd, encoding='UTF-8')

答案 1 :(得分:0)

我不确切知道你的p.communicate()方法是做什么的,但似乎它返回一个字节对象作为结果。而这段代码,无法将此字节对象添加到"错误raxml" str对象:

assert p.returncode == 0,"Error raxml"+out[0]

也许您应该尝试将其转换为str:

assert p.returncode == 0,"Error raxml"+str(out[0])