从python2.7迁移到3.8:“TypeError:需要一个byteslike对象,而不是'str'”

2024-04-26 17:45:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在我看到的一个文件中:

"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

Tags: 文件selfcmdchildoutputbytesobjectis
1条回答
网友
1楼 · 发布于 2024-04-26 17:45:33

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

>>> b'multi\nline'.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

一种修复方法是使用split(b"\n")。但是由于您是在行尾拆分,我猜您的命令会返回文本,因此更好的解决方案是将text=True传递给subprocess.Popen()cmd的输出将被直接解码,这将有助于查看任何编码错误,而您最适合处理这些错误。你知道吗

另外,考虑在python3的端口结束时使用subprocess.run(),因为它比subprocess.Popen更易于使用。你知道吗

相关问题 更多 >