【问题标题】:Python Unicode and \xe2\x80\x98r\xe2\x80\x99 errorPython Unicode 和 \xe2\x80\x98r\xe2\x80\x99 错误
【发布时间】:2018-11-04 11:03:33
【问题描述】:

Python 版本 3.5.2

所以我有来自mitmproxy 的文件输出称为enter code here,我想使用以下方法读取它:

from shelljob import proc

g = proc.Group()
command = "tail -f -c +0 output_file | mitmdump -n -r - --set flow_detail=1 --showhost"
p = g.run (command)

def read_process():
    while g.is_pending():
        lines = g.readlines()
        for proc, line in lines:
            print ("data:" + str(line) + '\n\n')

返回

data:b'tail: invalid number of lines: \xe2\x80\x98r\xe2\x80\x99\n'

但如果我将命令更改为ping 127.0.0.1,例如:

from shelljob import proc

g = proc.Group()
command = "ping 127.0.0.1"
p = g.run (command)

def read_process():
    while g.is_pending():
        lines = g.readlines()
        for proc, line in lines:
            print ("data:" + str(line) + '\n\n')

它工作正常!返回:

data:b'64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.056 ms\n'

那么解决办法是什么?

【问题讨论】:

  • 您是否尝试在脚本文件的顶部添加`# -- coding: utf-8 --`?
  • 我已经尝试添加# -- coding: utf-8 --,但同样的错误@LISHITING
  • 那么,你到底在问什么?为什么您的命令 tail -f -c +0 output_file | mitmdump -n -r - --set flow_detail=1 --showhost 无法按预期工作以及如何解决?因为从我的角度来看,输出的编码对您来说似乎并不像问题所暗示的那样严重
  • @LISHITING 该声明只声明了源文件的编码。如果源文件全是 ASCII(如图所示),则没有区别。

标签: python unicode character-encoding


【解决方案1】:

数据以字节为单位返回,如输出前面的b 所示。 您必须将其解码为字符串。

print ("data:" + line.decode('utf-8') + '\n\n')

【讨论】:

  • 再次出错.. 并返回tail: invalid number of lines: ‘r’
  • 是的。这是命令行上的命令产生的错误。它与python无关。另外,请参阅 metatoaster 对此的回答
【解决方案2】:

我很确定在调用 g.run 时,您的命令没有像您预期的那样通过管道传输 - 在 mitmdump 之后的参数 -n -r 以某种方式传递给 tail,因此运行以下命令:

$ tail -n -r
tail: invalid number of lines: ‘r’

生成您看到的错误消息。

现在您告诉我们g.run 究竟是什么,查看函数的documentation,我们可以看到它需要一个shell 参数,该参数传递给Popen,这是启用处理 shell 命令。要解决此问题,您可以尝试以下方法:

p = g.run(command, shell=True)

【讨论】:

  • 抱歉,我更新了我的代码。我跟着教程来自:mortoray.com/2014/03/04/…
  • 当您直接从 Python 外部的命令行运行命令时,屏幕上是否会打印任何内容?
  • 然后它以完全相同的方式工作。您确定output_file 正在写入数据吗?运行tail -f output_file 提供什么?
  • 我确定output_file 中有数据。如果我将命令更改为tail -f -c +0 output_file 并更改shell=False,它将打印与tail -f output_file 相同的二进制文本..
  • 不是通过管道连接到mitmdump,而是通过管道连接到像cat 这样中性的东西,看看它在Python 代码中的工作方式是否与在命令行中的工作方式相同。
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 2023-03-21
相关资源
最近更新 更多