python struct_Python,13万中文库,核心模块学习第六章

Those people who have nothing better to do than post on the Internet all day long are rarely the ones who have the most insights

那些整天在网上无所事事的人很少是最有洞察力的人

五年前我偶然遇到了 Python, 开始了我的 Python 之旅, 我花费了大量的时间在Python模块上面,如果一个模块正是我们想要的, 但是却不知道如何使用它.是一件非常痛苦的事情

Python 的标准库包括了很多的模块, 从 Python 语言自身特定的类型和声明,

到一些只用于少数程序的不著名的模块.

本章描述了一些基本的标准库模块. 任何大型 Python 程序都有可能直接或间

接地使用到这类模块的大部分.

struct 模块

struct 模块用于转换二进制字符串和 Python 元组. pack 函数接受格式字符

串以及额外参数, 根据指定格式将额外参数转换为二进制字符串. upack 函数

接受一个字符串作为参数, 返回一个元组

37de3c93d37e951c01ec0c89960ec672.png

使用 struct 模块

import struct

# native byteorder

buffer = struct.pack("ihb", 1, 2, 3)

print repr(buffer)

print struct.unpack("ihb", buffer)

# data from a sequence, network byteorder

data = [1, 2, 3]

buffer = apply(struct.pack, ("!ihb",) + tuple(data))

print repr(buffer)

print struct.unpack("!ihb", buffer)

# in 2.0, the apply statement can also be written as:

# buffer = struct.pack("!ihb", *data)

'001000000000002000003'

(1, 2, 3)

'000000000001000002003'

(1, 2, 3)

xdrlib 模块

xdrlib 模块用于在 Python 数据类型和 Sun 的 external data

representation (XDR) 间相互转化, 如 Example 4-7 所示.

使用 xdrlib 模块

File: xdrlib-example-1.py

import xdrlib #

# create a packer and add some data to it

p = xdrlib.Packer()

p.pack_uint(1)

p.pack_string("spam")

data = p.get_buffer()

print "packed:", repr(data)

#

# create an unpacker and use it to decode the data

u = xdrlib.Unpacker(data)

print "unpacked:", u.unpack_uint(), repr(u.unpack_string())

u.done()

packed: '000000000001000000000004spam'

unpacked: 1 'spam'

Sun 在 remote procedure call (RPC) 协议中使用了 XDR 格式. Example 4-8

虽然不完整, 但它展示了如何建立一个 RPC 请求包.

使用 xdrlib 模块发送 RPC 调用包

import xdrlib

# some constants (see the RPC specs for details)

RPC_CALL = 1

RPC_VERSION = 2

MY_PROGRAM_ID = 1234 # assigned by Sun

MY_VERSION_ID = 1000

MY_TIME_PROCEDURE_ID = 9999

AUTH_NULL = 0

transaction = 1

p = xdrlib.Packer() # send a Sun RPC call package

p.pack_uint(transaction)

p.pack_enum(RPC_CALL)

p.pack_uint(RPC_VERSION)

p.pack_uint(MY_PROGRAM_ID)

p.pack_uint(MY_VERSION_ID)

p.pack_uint(MY_TIME_PROCEDURE_ID)

p.pack_enum(AUTH_NULL)

p.pack_uint(0)

p.pack_enum(AUTH_NULL)

p.pack_uint(0)

print repr(p.get_buffer())

'000000000001000000000001000000000002000000004322

000000003350000000'017000000000000000000000000000

000000000000000000000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值