2012-05-24 4 views
1

파이썬의 csv.writer로 생성 한 .csv 파일을 bcp하려고 할 때 EOF 문제가 있습니다. 나는 행운과 인터넷 검색을 많이 해봤 그래서 나는 SO파이썬 하위 프로세스 .csv : 'unexpected eof'

에 당신이 도움이 사람에 켜 여기합니다 (subprocess.call() 라인에 트리거) 오류 메시지입니다 :

Starting copy... 
Unexpected EOF encountered in BCP data-file. 
bcp copy in failed 

여기가 코드 :

sel_str = 'select blahblahblah...' 
result = engine.execute(sel_str) #engine is a SQLAlchemy engine instance 

# write to disk temporarily to be able to bcp the results to the db temp table 
with open('tempscratch.csv','wb') as temp_bcp_file: 
    csvw = csv.writer(temp_bcp_file) 
    for r in result: 
     csvw.writerow(r) 
     temp_bcp_file.flush() 

# upload the temp scratch file 
bcp_string = 'bcp tempdb..collection in @INFILE -c -U username -P password -S DSN' 
bcp_string = string.replace(bcp_string,'@INFILE','tempscratch.csv') 
result_code = subprocess.call(bcp_string, shell=True) 

나는 텍스트 편집기에서 tempscratch.csv 파일을 보았고, 어떤 이상한 EOF 또는 기타 제어 문자를 보지 않았다. 또한 비교를 위해 다른 .csv 파일을 조사했는데 bcp가 찾고있는 표준화 된 EOF가없는 것 같습니다.

또한이 결과는 디스크에 기록한 다음 bcp를 사용하여 db에 다시 업로드하는 결과입니다. SQLAlchemy가 동일한 execute() 명령에서 여러 줄 문 (일명 DDL 및 DML)을 지원하지 않기 때문에이 작업을 수행해야합니다. 또한,이 연결은 SQLAlchemy의 멋진 ORM을 지원하지 않는 Sybase DB와 연결됩니다. (이것이 내가 처음에 execute()를 사용하는 이유입니다)

+0

당신이'bcp_string'을 인쇄 터미널에서 그것을 실행하려고 적이 있습니까? 아마 명령 문자열은 잘못 'shell = True'를 피해야한다.'[ "bcp", "tempdb..collection", "in", ...]'과 같이 실행 파일의 이름과 인수 목록을 생성하여 명령을 컴파일한다. –

+0

@ Jan-PhilipGehrcke 문자열은 정확하지만 bcp 명령은 동일한 오류를 반환합니다. 깔창. 또한, 보안 팁 주셔서 감사합니다 :) – ignorantslut

+0

나는 아직도 무엇이 잘못 되었는가 전혀 모르겠지만 코드에 한가지 더 말합니다 : 왜'flush()'호출이 필요한가요? 'with' 문맥을 남긴 후에, 파일은 적절히 닫히고 버퍼는 물론 전에 플러시되었습니다. –

답변

5

bcp 기본 필드 구분 기호 쉼표로 파이썬의 CSV 작가 기본값 동안 탭 문자 '\의 t'.이 시도 ...

# write to disk temporarily to be able to bcp the results to the db temp table 
with open('tempscratch.csv','wb') as temp_bcp_file: 
    csvw = csv.writer(temp_bcp_file, delimiter = '\t') 
    for r in result: 
     csvw.writerow(r) 
    temp_bcp_file.flush() 
+0

피 묻은 화려한, 트릭을 한 :) 감사합니다 !! – ignorantslut

+0

'.flush()'는 여기서 불필요합니다. – jfs

관련 문제