放分组显示()字符串变量的表示

2024-03-28 13:10:13 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能把Packet.show()给我的表示放入一个字符串变量中?在

像这样

representation = somePacket.show()
print representation # will print nothing

这样我就可以把它储存起来供以后使用,并在需要时打印出来?在


Tags: 字符串packetshowwillprintnothingrepresentationsomepacket
1条回答
网友
1楼 · 发布于 2024-03-28 13:10:13

.show()只需打印到stdout。您需要将sys.stdout替换为可以保存写入字符串的对象。在

例如,在下面的示例中,io.BytesIO用于捕获写入的字符串:

>>> import sys
>>> from io import BytesIO
>>> from scapy.all import Ether, IP, ICMP, Net
>>> packets = Ether()/IP(dst=Net("google.com/30"))/ICMP() 
>>> old_stdout, sys.stdout = sys.stdout, BytesIO()
>>> try:
...     packets.show()
...     output = sys.stdout.getvalue()  # retrieve written string
... finally:
...     sys.stdout = old_stdout  # Restore sys.stdout
... 
>>> output[:10]
'###[ Ether'

相关问题 更多 >