2012-10-23 4 views
0

내가 파이썬에 새로운 오전 및 StackOverflow의에서 정말 큰 도움과 함께, 내가 프로그램을 작성했습니다 :파이썬 함수를 어떻게 구조화하여 에러가 발생하더라도 계속 진행할 수 있습니까?

2 :

1) 주어진 디렉토리에 보이는을, 해당 디렉토리에있는 각 파일에 대한

  • 는 블랙리스트 태그를 & 내용
  • Prettifies 나머지 계속을 제거
  • BeautifulSoup로 각 파일을 엽니 다 :)는 HTML 청소 프로그램을 실행 엔트
  • 는 무리를 던졌습니다 파일 내용의 특정 종류 안타 경우를 제외하고는
  • 이 아주 잘 새로운 파일이 작동

로 출력 저장 속성 & 모든 비 화이트리스트 태그를 제거하기 위해 표백제를 실행 BeautifulSoup 오류가 발생하여 모든 것을 중단합니다. 이 디렉터리에서 어떤 종류의 콘텐츠가 나올지 제어 할 수는 없으므로이를 강력하게 원합니다.

내 질문은 : 어떻게하면 디렉터리 내의 한 파일에서 오류가 발생할 때 해당 파일을 처리 할 수 ​​없다고보고하고 나머지 파일을 계속 실행하도록 프로그램을 다시 구성 할 수 있습니까? 파일? 여기

는 (제거 불필요한 세부 사항) 지금까지 내 코드입니다 : 나는 계속 실행되도록이를 작성하는 방법에 대한 지침을 찾고

def clean_dir(directory): 
    os.chdir(directory) 

    for filename in os.listdir(directory): 
    clean_file(filename) 

def clean_file(filename): 

    tag_black_list = ['iframe', 'script'] 
    tag_white_list = ['p', 'div'] 
    attr_white_list = {'*': ['title']} 

    with open(filename, 'r') as fhandle: 

     text = BeautifulSoup(fhandle) 
     text.encode("utf-8") 
     print "Opened "+ filename 

     # Step one, with BeautifulSoup: Remove tags in tag_black_list, destroy contents. 
     [s.decompose() for s in text(tag_black_list)] 
     pretty = (text.prettify()) 
     print "Prettified" 

     # Step two, with Bleach: Remove tags and attributes not in whitelists, leave tag contents. 
     cleaned = bleach.clean(pretty, strip="TRUE", attributes=attr_white_list, tags=tag_white_list) 

     fout = open("../posts-cleaned/"+filename, "w") 
     fout.write(cleaned.encode("utf-8")) 
     fout.close() 

    print "Saved " + filename +" in /posts-cleaned" 

print "Done" 

clean_dir("../posts/") 

구문 분석/인코딩/컨텐츠를 타격 후/clean_file 함수 내에서/etc에 오류가 있습니다.

+3

BS가 던진 예외를 잡습니다. –

+2

http://docs.python.org/tutorial/errors.html#user-defined-exceptions을 참조하십시오 "시도하십시오"및 "제외"는 귀하의 친구입니다 :) – cb0

답변

1

당신은 루프 clean_file 내부 또는에서 오류 처리를 할 수 있습니다.

어떤 예외가 발생하는지 알면보다 구체적인 catch를 사용할 수 있습니다.

관련 문제