[위 에]python.struct helper class
/*!
python struct helper class
version : 0.01
created by : andrew.wu ([email protected])
created on : 2009/05/23
url : http://blog.oolanguage.com/erpingwu/python-struct-module-helper-class/
*/
python struct 는 사용 하기 좋 은 module 로 c struct 를 편리 하 게 처리 할 수 있 습 니 다.그러나 c struct 를 포맷 문자열 로 바 꾸 는 작업 은 좀 번 거 롭 습 니 다.효율 적 인 프로그래머 는 게 으 름 을 피 우 는 프로그래머 여야 합 니 다.번 거 로 운 작업 은 가능 한 한 자동화 해 야 합 니 다.c struct 는 복잡 하 게 쓸 수 있 지만 대부분 상대 적 으로 규범 적 입 니 다.그러면 먼저 간단 한 버 전 을 만들어 서 큰 지혜 를 설명 하 겠 습 니 다.-인 터 넷 버 전의 일 선 데이터 로 인 스 턴 스 를 만 들 겠 습 니 다.
struct DZHDay{
unsigned int trade_date; // ,
unsigned int open_price; // , 1000
unsigned int high_price; // , 1000
unsigned int low_price; // , 1000
unsigned int close_price; // , 1000
unsigned int turn_volume;// , 10
unsigned int trading_volume ; //
unsigned int private_investor_line; //
unsigned int unknown1; //
unsigned int unknown2; //
};
우선,python 이 struct 에 관 한 정 보 를 자동 으로 얻 을 수 있어 야 합 니 다.여 기 는 자신 이 무엇 을 실현 하지 않 고 모든 것 을 스스로 하 는 것 이 효율 을 높이 는 것 이 아니 라 자신 에 게 번 거 로 움 을 주 는 것 입 니 다.인터넷 에서 Cpp Header Parser.py 를 찾 으 면 이 일 을 완성 할 수 있 습 니 다.조금 만 수정 하면 됩 니 다.
line 427: if (tok.value == 'class' or tok.value == 'struct'):
line 452: elif (self.nameStack[0] == "class" or self.nameStack[0] == "struct"):
다음은 코드 를 붙 입 니 다.코드 가 무엇 보다 잘 나 오 는 것 같 습 니 다.t.py
# -*- coding: utf-8-*-
import os
from struct import *
from andrew.struct_helper import *
import binascii
dzh_day = '''
struct DZHDay{
unsigned int trade_date; // ,
unsigned int open_price; // , 1000
unsigned int high_price; // , 1000
unsigned int low_price; // , 1000
unsigned int close_price; // , 1000
unsigned int turn_volume;// , 10
unsigned int trading_volume ; //
unsigned int private_investor_line; //
unsigned int unknown1; //
unsigned int unknown2; //
};
''';
import unittest
class Tests(unittest.TestCase):
def setUp(self):
self.sh = StructHelper();
self.sh.parse(dzh_day, "DZHDay");
pass;
def tearDown(self):
pass
def testOne(self):
f = open(r"600050.day", 'rb');
data = f.read();
f.close()
nt = self.sh.namedtuple._make(unpack(self.sh.format_string,
data[0 : self.sh.unpack_size]));
#print nt
self.assertEqual(nt.trade_date, 20090521)
def testTwo(self):
#f = open(r"C:/dzh/DATA/SHase/Day/600388.day", 'rb');
f = open(r"600050.day", 'rb');
data = f.read();
f.close()
#print binascii.b2a_hex(data)
for index in range(0, len(data) / self.sh.unpack_size ):
nt = self.sh.namedtuple._make( unpack_from( self.sh.format_string,
data, self.sh.unpack_size*index) );
print "/n", nt
pass;
pass
def main():
unittest.main()
if __name__ == '__main__':
main()
struct_helper.py
# struct helper class
# version : 0.01 v
# created by : andrew.wu ([email protected])
# created on : 2009/05/23
import os
from struct import *
from collections import namedtuple
from CppHeaderParser import *
class StructHelper():
_struct_format_table = {
'pad byte':'x',
'char':'c',
'signed char':'b',
'unsigned char':'B',
'bool':'?',
'BOOL':'?',
'short':'h',
'unsigned short':'H',
'int':'i',
'unsigned int':'I',
'long':'l',
'unsigned long':'L',
'long long':'q',
'unsigned long long':'Q',
'float':'f',
'double':'d',
'char[]':'s',
'void *':'P'
}
def type_to_fmt(self, type):
return self._struct_format_table[type];
pass;
def parse(self, code, struct_name):
self.format_string = ""
self.named_string = ""
cpp_header = CppHeader(code , argType = "string")
properties = cpp_header.classes[struct_name]["properties"]["private"]
for p in properties:
self.format_string += self.type_to_fmt(p["type"])
self.named_string += p["name"] + " "
self.unpack_size = calcsize(self.format_string)
self.namedtuple = namedtuple(struct_name, self.named_string)
pass;
pass;
output . DZHDay(trade_date=20090521, open_price=6400, high_price=6410, low_price=6180, cl ose_price=6240, turn_volume=2085205, trading_volume=3334743, private_investor_li ne=373549, unknown1=4857, unknown2=2136735744) DZHDay(trade_date=20090522, open_price=6210, high_price=6290, low_price=6170, cl ose_price=6260, turn_volume=1023114, trading_volume=1639956, private_investor_li ne=385,unknown 1=4873,unknown 2=0).http://sourceforge.net/projects/cppheaderparser/ PLY (Python Lex-Yacc) 3.2 http://www.dabeaz.com/ply/ Python 2.6 http://www.python.org/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JS_3. 내장객체Math는 전역객체이기 때문에 new 키워드 사용하지 않음 new Object() 대신 { } 사용가능 new Array() 대신 [ ] 사용가능 new String()대신 " " 사용가능 new Boolean()대...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.