【问题标题】:unexpected extra backslash when reading data from stdout using subprocess使用子进程从标准输出读取数据时出现意外的额外反斜杠
【发布时间】:2021-02-08 06:40:08
【问题描述】:

我有一个 python 源代码(名称为source.py),它显示一些数据,例如

b'testdata \xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00@\x00\......

在终端上。

我想获取这些信息并将它们保存在一个变量中,所以我写了这段代码:

import subprocess

    
batcmd= 'python3.8 source.py'
result = subprocess.check_output(batcmd, shell=True)
print (result)

输出:

b'testdata \\xe3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1f\\x00\\x00\\x00@\\x00\\......

问题是任何\ 都会重复2次!

我该如何解决这个问题?

注意事项:

1 - 我无法编辑 source.py!我不能操纵它,我们只能阅读 来自终端的数据。

2 - 我最近使用了_w_long_,然后我编辑了我的帖子并 algorithm ,所以如果你在 cmets 中看到它,那是因为,忽略它。

3- 存储的数据必须保留在 字节

更新:

我也试过了:

from contextlib import redirect_stdout
import io,os


res = os.popen("decompyle3 start.py.pyc").read()
print (res)

print (res.encode('latin1'))

在此代码中:print(res),将在输出中打印此数据类型为字符串

"b'\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00@\x00\x00\x00sV\x00\x00\x00e\x00e\x01d\x00d\x01\x84\x00d\x02d\x03d\x03d\x04d\x05d\x06d\x07d\x08d\td\x03d\x03d\nd\x0bd\x05d\x0cd\x08d\rd\x0ed\x0cd\x0fd\..."

所以我想将此字符串转换为字节而不做任何更改,我想要这个输出:

b'\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00@\x00\x00\x00sV\x00\x00\x00e\x00e\x01d\x00d\x01\x84\x00d\x02d\x03d\x03d\x04d\x05d\x06d\x07d\x08d\td\x03d\x03d\nd\x0bd\x05d\x0cd\x08d\rd\x0ed\x0cd\x0fd\...

我试过了:

print (res.encode('latin1'))

打印出来的:

b\'\\xe3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1f\\x00\\x00\\x00@\\x00\\x00\\x00sV\\x00\\x00\\x00e\\x00e\\x01d\\x00d\\x01\\x84\\x00d\\x02d\\x03d\\x03d\\x04d\\x05d\\x06d\\x07d\\x08d\\td\\x03d\\x03d\\nd\\x0bd\\x05d\\x0cd\\x08d\\rd\\x0ed\\x0cd\\x0fd...

我们看到任何\ 重复!

如何解决这个问题?

【问题讨论】:

  • The marshal format changes from version to version:“Python 维护者保留在需要时以向后不兼容的方式修改 marshal 格式的权利。”所以marshaled 在版本X.Y 中的某些东西不能保证在版本X.Y+1 中是不可编组的(反之亦然)。为什么你希望它在所有版本的 Python 中都能正常工作?
  • 是的,编组格式和算法正在改变,但是 _w_long lib 呢?这个库在 python3.8 及更高版本中不存在吗?
  • _w_long 是一个内部实现细节(你可以通过前导下划线来判断)。它不能保证会留下来,没有人应该依赖它。

标签: python-3.x subprocess hex stdout encode


【解决方案1】:
from contextlib import redirect_stdout
import io,os

with io.StringIO() as buf, redirect_stdout(buf):
    os.system("python3.8 source.py")
    res = buf.getvalue()
    print(res)

【讨论】:

  • 此脚本仅获取标准输出。 ,我已经使用subprocess.check_output(batcmd, shell=True) 来获取它。我的问题是将此获取的字符串转换为字节,并在 `\` 中有任何重复
猜你喜欢
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多