【问题标题】:Migrating from Python 2.7 to 3.8: "TypeError: a bytes-like object is required, not 'str'"从 Python 2.7 迁移到 3.8:“TypeError:需要类似字节的对象,而不是 'str'”
【发布时间】:2019-12-17 11:08:42
【问题描述】:

在我看到问题的文件之一中:

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

代码sn-p:

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

【问题讨论】:

    标签: python python-3.x python-2to3


    【解决方案1】:

    由于您在没有text=True 的情况下调用了subprocess.Popen(),因此Popen.communicate() 会返回记录的字节,并且您不能使用字符串拆分字节。您可以使用以下 sn-p 重现您的错误:

    >>> 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 的输出将被立即解码,这将有助于查看您最有能力处理的任何编码错误。

    另外,在 Python 3 的移植结束时考虑使用subprocess.run(),因为它比subprocess.Popen 更易于使用。

    【讨论】:

    • 在将 Popen 更改为运行或添加 text=True 时,获取“builtin_function_or_method”对象没有“子进程”属性。
    • 备选 1:def run_process(self, cmd): sh = self.is_win() child = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh) output = child.communicate()[0].strip().split('\n') 返回输出,child.returncode
    • Alternate2: def run_process(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
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多