python - 类型错误 : Can't convert 'bytes' object to str implicitly using Python3. 5

标签 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]

这根本没有解决问题。我看过类似的问题,但我无法提出解决方案。我将不胜感激。

谢谢!

最佳答案

p,一个 Popen 对象,没有 .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')

关于python - 类型错误 : Can't convert 'bytes' object to str implicitly using Python3. 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49844618/

相关文章:

python - Aerospike Python 客户端中的段错误

Python - 再次显示 'once' 警告(重置所有警告注册表)

python - 如何使用自定义标记颜色将每个句子包装在标签中?

python - 当我编辑详细信息时,Django 表单正在添加字符

Python IndexError - 需要帮助排序键和值

python - 测试依赖于硬件的 Python 代码

python - 无法使用pypyodbc在python中使用where子句运行mssql select查询

python - 远程服务器上的 Django 调试工具栏

python - 将不同数据框中的 2 列与主键条件进行比较,无需合并

Python 脚本打印 unicode,在 shell ` ` 中使用导致错误