【问题标题】:Python3 compatability with file objectPython3 与文件对象的兼容性
【发布时间】:2020-09-02 22:43:50
【问题描述】:

我有一个类/对象,它是 linux 中一堆 cmd 的子进程。该对象具有以下内容:

def __enter__(self):
    self.proc = subprocess.Popen(self.cmd, bufsize=-1, shell=True, stdout=subprocess.PIPE, executable="/bin/bash")
    return self.process.stdout 

这基本上在 Python2 中返回一个 file 对象,在 Python3 中返回一个 _io.BufferedReader

我在每一行上执行一堆逻辑并创建一堆生成器。什么是同时支持 python 2 和 3 的最佳方式。例如,如果我有类似的东西

line = input_file.next().strip().split(' ')

适用于 Python 2,但对于 Python 3,我会得到类似的东西

`_io.BufferedReader` object has no attribute 'next'

如果我将input_file.next() 更新为input_file.readline(),我会收到以下错误:

a bytes-like object is required, not 'str'

我可以相应地更新它以适用于 Python3,但是有没有更好的方法来做到这一点,而无需在每种情况下完全不同的算法/逻辑?

【问题讨论】:

    标签: python file io backwards-compatibility


    【解决方案1】:

    顶级内置函数 next 可在 Python 2 和 Python 3 上运行,因此请使用 input_file.next() 代替 input_file.next()。至于始终分割 ASCII 空格字符,只需在要分割的字符串上加上 b 前缀即可;它在 Python 2 上没有任何改变(b' '' ' 相同,在 Python 2 上都是 str),在 Python 3 上,它使其成为 bytes 对象(二进制模式 Popen 进程产生) .

    最终版本的代码是:

    line = next(input_file).strip().split(b' ')
    

    并且在 Python 2 和 Python 3 上的工作方式相同。

    【讨论】:

    • 抱歉忘记在这里回复了。我的问题实际上是在我得到这段代码之前,但这绝对有帮助,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多