从Python2.7迁移到3.8:;TypeError:需要类似字节的对象,而不是';str'&引用;

从Python2.7迁移到3.8:;TypeError:需要类似字节的对象,而不是';str'&引用;,python,python-3.x,python-2to3,Python,Python 3.x,Python 2to3,在我看到的其中一个文件中,出现了以下问题: "TypeError: a bytes-like object is required, not 'str'" 代码段: def run_process(self, cmd): sh = self.is_win() child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh) outpu

在我看到的其中一个文件中,出现了以下问题:

"TypeError: a bytes-like object is required, not 'str'"
代码段:

def run_process(self, cmd):
        sh = self.is_win()
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh)
        output = child.communicate()[0].strip().split('\n')
        return output, child.returncode

由于调用
subprocess.Popen()
时未使用
text=True
Popen.communicate()
返回文档中的字节,因此不能使用字符串拆分字节。您可以使用以下代码段再现错误:

>b'multi\n行'.split('\n')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要类似字节的对象,而不是“str”
一种修复方法是使用
split(b“\n”)
。但是由于您是在行尾拆分,我想您的命令会返回文本,因此更好的解决方案是将
text=True
传递给
subprocess.Popen()
cmd
的输出将被直接解码,这将有助于查看您最适合处理的任何编码错误


还考虑使用<代码>子进程.Run()/>代码>当Python 3结束时,它比<代码>子进程> Popen < /COD> .< /P>获取“BuffTIN函数-OrthOrthPosiod”对象没有属性“子进程”来改变POPON以运行或添加文本= true.交替1:DEF RunuPalm(自,CMD):SH=Sur. IsWin()child=subprocess.run(cmd,stdout=subprocess.PIPE,stderr=subprocess.stdout,shell=sh)output=child.communicate()[0].strip().split('\n')返回输出,child.returncodeAlternate2:def run_进程(self,cmd):sh=self.is_win()child=subprocess.Popen(cmd,text=True,stdout=subprocess.PIPE,stderr=subprocess.stdout,shell=sh)output=child.communicate()[0].strip().split('\n')返回输出,child.returncode