2011-12-12 5 views
0

파일을 지정된 너비의 세그먼트로 나누는 소비자 프로그램이 세그먼트를 가져 와서 원본 파일의 복사본을 만듭니다. 세그먼트가 잘못되어 있으므로 오프셋 값을 사용하여 파일에 쓰려고합니다. 받는 쪽의 모든 데이터를 보유 할 로컬 배열을 만들지 않고이 방법을 사용할 수 있습니까? 예를 들어오프셋을 기반으로 파일에 파이썬 쓰기

,

f = open(file, "wb") 
f.seek(offset) 
f.write(data) 

이 뒤에 아이디어는 파일을 전송하는 프로그램이 파일을 전송 완료하지 못할 수도 있습니다, 그리고 그것을 시작되면 다시 재개 할 것입니다. 버퍼 위치에 데이터를 배치하려고 할 때 "combine_bytes"함수가 예외를 throw하는 샘플 코드가 있습니다.

import sys 
import os 

def SplitFile(fname, start, end, width): 
    t_fileSize = os.path.getsize(fname) 
    buffData = bytearray(t_fileSize) 
    for line, offset in get_bytes(fname, int(start), int(end), int(width)): 
    combine_bytes(buffData, offset, line, width)   
     nums = ["%02x" % ord(c) for c in line] 
     print " ".join(nums) 

    f = open("Green_copy.jpg", "wb") 
    f.write(buffData) 
    f.close() 


def combine_bytes(in_buff, in_offset, in_data, in_width): 
    #something like memcpy would be nice 
    #in_buff[in_offset:in_offset + in_width] = in_data 

    #this works but it's the mother of inefficiency 
    i = in_offset 
    for c in in_data: 
     in_buff.insert(i, c) 
     i = i + 1 


def get_bytes(fname, start, end, width): 
    t_currOffset = start 
    t_width = width 
    f = open(fname, "r+b") 

    if end != 0: 
    while t_currOffset < end: 
     f.seek(t_currOffset) 
     if (t_currOffset + t_width) > end: 
      t_width = end - t_currOffset 
     t_data = f.read(t_width) 
     yield t_data,t_currOffset 
     t_currOffset += t_width 
    else: 
    f.seek(t_currOffset) 
    t_data = f.read(t_width) 
    while t_data: 
     yield t_data, t_currOffset 
     t_currOffset += t_width 
     f.seek(t_currOffset) 
     t_data = f.read(t_width) 

    f.close() 


if __name__ == '__main__': 
    try: 
    SplitFile(*sys.argv[1:5]) 
    except: 
    print "Unexpected error:", sys.exc_info()[0] 
+0

자세한 정보가 필요하시면 알려주세요. 코드에 이해하기 쉽거나 테스트하기 어려운 몇 개의 들여 쓰기 오류가 있습니다. (첫 번째'for '안에있는 combine_bytes 호출과 같이 - 다른 레벨에 들여 쓰기해야합니다.) – jsbueno

답변

0

발견. 여기 내가 원하는 것을 만들어 내고 더 빨리 만드는 더 좋은 방법입니다. _buffData[t_offset:t_offset + len(t_data)] = bytearray(t_data)

1

난 여전히 당신의 의도가 무엇인지 파악 NT 수 -의

def combine_bytes(in_buff, in_offset, in_data, in_width): 
    #something like memcpy would be nice 
    #in_buff[in_offset:in_offset + in_width] = in_data 

    in_buff = in_buff[:in_offset] + in_data + in_buff[in_offset:] 
    return in_buff 

(실제로는 정확히를 인) 부분을 당신의 "당신의 비 효율성의 어머니"를 제거하지만 combine_bytes이 버전의 물론이 각 통화에 대한 새로운 (더 큰) 버퍼를 작성, 당신은 하나 발신자 범위에 버퍼를 교체해야 반환

buffData = combine_bytes(buffData, offset, line, width)

+0

나는 내가 분명하다고 생각해서 미안합니다. 어느 부분이 불분명합니까? 그리고 코드가 트릭을했습니다! – ArmenB

+0

사실, 내가 선을 뒤섞었을 때,이 코드는 잘못된 순서로 붙어있었습니다. 'code''code' – ArmenB

+0

그것을 찾았습니다. 여기 내가 원하는 것을 만들어 내고 더 빨리 만드는 더 좋은 방법입니다. '_buffData [t_offset : t_offset + len (t_data)] = bytearray (t_data)' – ArmenB