【问题标题】:Retry failed readline of stdout with different encoding使用不同的编码重试失败的标准输出读取行
【发布时间】:2022-01-18 03:34:47
【问题描述】:

使用 Python,我正在运行一个 jmeter 进程,使用以下代码:

with subprocess.Popen(jmeterscript, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", shell=True) as process:
    while True:
        line = process.stdout.readline().strip()
        if line == '':
            break
        print(line)
        retval += line

但是我的脚本在 readline 调用中抛出了一个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 555: invalid continuation byte

因为它检测到一个 latin-1 字符 (0xE9),它与 ​​utf-8 编码不兼容。

我想捕获此异常并尝试使用不同的编码(或仅字节)打印出标准输出行,以帮助我识别损坏的行。但是因为它在一个stdout utf-8进程的中间,所以我想不出该怎么做。

【问题讨论】:

  • 如果这是在 Windows 上,如我所料,那么您可能希望在启动进程时指定 encoding='cp1252'。
  • 谢谢,但脚本包含 utf-8 字符并需要它们。当它遇到 Latin-1 字符时,我希望它会引发错误,并且我想捕获异常。

标签: python subprocess pipe stdout python-unicode


【解决方案1】:

我想出了一种方法来做到这一点,即将编码设置为无并将每一行解码为一个字符串。有更多的灵活性,我可以将有问题的行打印为字节:

    with subprocess.Popen(strtorun, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=None, shell=True) as process:
        while True:
            line = process.stdout.readline().strip()
            try:
                line = line.decode("utf-8")
            except UnicodeDecodeError:
                print("\n*Output has invalid (non utf-8) characters! Invalid output: {}\n".format(line))
                raise
            if line == '':
                break
            print(line)
            retval += line

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多