使用子进程从stdout读取数据时出现意外的额外反斜杠

问题描述

我有一个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_,然后编辑了自己的帖子, 算法,所以如果您在注释中看到它,那是因为忽略它。

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...

我们看到任何\被重复!

如何解决这个问题?

解决方法

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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...