gpt4 book ai didi

python - 使用 universal_newlines=True(bufsize=1)和使用 Popen 的默认参数有什么区别

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:25 24 4
gpt4 key购买 nike

我正在尝试读取从 Python 调用的子进程的输出。为此,我使用 Popen(因为我认为如果使用 subprocess.call 则无法通过管道传输标准输出)。

截至目前,我有两种方法可以做到这一点,在测试中,它们似乎提供了相同的结果。代码如下:

with Popen(['Robocopy', source, destination, '/E', '/TEE', '/R:3', '/W:5', '/log+:log.txt'], stdout=PIPE) as Robocopy:
for line in Robocopy.stdout:
line = line.decode('ascii')
message_list = [item.strip(' \t\n').replace('\r', '') for item in line.split('\t') if item != '']
print(message_list[0], message_list[0])
Robocopy.wait()
returncode = Robocopy.returncode

with Popen(['Robocopy', source, destination, '/E', '/TEE', '/R:3', '/W:5', '/log+:log.txt'], stdout=PIPE, universal_newlines=True, bufsize=1) as Robocopy:
for line in Robocopy.stdout:
message_list = [item.strip() for item in line.split('\t') if item != '']
print(message_list[0], message_list[2])
Robocopy.wait()
returncode = Robocopy.returncode

第一种方法不包括 universal_newlines=True,因为文档说明这是 only usable if universal_newlines=True i.e., in a text mode .

第二个版本确实包含 universal_newlines,因此我指定了一个 bufsize。

有人能给我解释一下区别吗?我找不到这篇文章,但我确实读到了有关导致某种问题的缓冲区溢出问题以及使用 for line in stdout 的重要性。 .

此外,在查看输出时,不指定 universal_newlines 会使标准输出成为 bytes对象 - 但我不确定如果我只用 ascii 解码字节对象会有什么不同? (就换行符和制表符而言)比较了 universal_newlines 模式。

最后,设置 bufsize1使输出“行缓冲”,但我不确定这意味着什么。如果能解释一下这些不同的元素是如何结合在一起的,我将不胜感激。谢谢

最佳答案

What is the difference between using universal_newlines=True (with bufsize=1) and using default arguments with Popen

默认值为:universal_newlines=False(表示输入/输出被接受为字节,而不是Unicode 字符串加上 universal newlines mode 处理(因此是参数的名称。Python 3.7 提供了 text 别名,这里可能更直观)被禁用——您按原样获得二进制数据(除非 POSIX 层在Windows 把它搞砸了)和 bufsize=-1(意味着流被完全缓冲——使用默认缓冲区大小)。

universal_newlines=True 使用 locale.getpreferredencoding(False) 字符编码来解码字节(这可能与您使用的 ascii 编码不同代码)。

如果 universal_newlines=Falsefor line in Robocopy.stdout: 遍历 b'\n' 分隔的行。如果进程使用非 ascii 编码,例如 UTF-16 作为其输出,那么即使 os.linesep == '\n' 在您的系统上;你可能会得到错误的结果。如果您想使用文本行,请使用文本模式:明确传递 universal_newlines=True 或使用 io.TextIOWrapper(process.stdout)

The second version does include universal_newlines and therefore I specify a bufsize.

通常,如果您使用universal_newlines,则不必指定bufsize(您可以但不是必需的)。而且您不需要在您的情况下指定 bufsizebufsize=1 启用行缓冲模式(如果您要写入 process.stdin,输入缓冲区会在换行时自动刷新)否则它等同于默认的 bufsize=-1.

关于python - 使用 universal_newlines=True(bufsize=1)和使用 Popen 的默认参数有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38181494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com