如何解决使用子进程从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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。