zoukankan      html  css  js  c++  java
  • python模块struct和subprocess

    准确地讲,Python没有专门处理字节的数据类型。但由于str既是字符串,又可以表示字节,所以,字节数组=str。而在C语言中,我们可以很方便地用struct、union来处理字节,以及字节和int,float的转换。

    好在Python提供了一个struct模块来解决str和其他二进制数据类型的转换。

    structpack函数把整数类型变成字节:

    import struct
    
    res=struct.pack('i',16243422)
    print(res)                  
    print(len(res))
    
    >>>
    b'xdexdaxf7x00'
    4

    'i' 表示4字节无符号整数, 'h' 表示2字节无符号整数(范围:(-32768) <= number <= 32767)

    struct的unpack函数把字节类型还原成整数:

    import struct
    
    res=struct.pack('i',16243422)
    
    ret=struct.unpack('i',res)
    print(ret[0])
    
    >>>
    16243422

    所以,尽管Python不适合编写底层操作字节流的代码,但在对性能要求不高的地方,利用struct就方便多了。

    subprocess的popen用法:

    import  subprocess
    
    res=subprocess.Popen('dir',
                         shell=True,
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE)
    
    print(res.stdout.read().decode('gbk'))   #打印当前文件下的目录
    print(res.stderr.read().decode('gbk'))  #文件名输入错误,输出错误
  • 相关阅读:
    AD9 如何画4层pcb板
    在Altium Designer 2009下如何添加Logo图
    [置顶] 整数拆分 整合算法
    altium designer 中的top/bottom solder和top/bottom paste mask
    vs2012 与 win7 不兼容的问题
    poj1742 Coins
    poj3181 Dollar Dayz
    poj1065 Wooden Sticks
    poj1631 Bridging signals
    poj3666 Making the Grade
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/9585282.html
Copyright © 2011-2022 走看看