我在以下代码中使用 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/