Python File Crawler
## @brief 파일을 임시파일에 저장하고 임시파일의 경로와 실제 파일이름을 리턴합니다.
# @param url 대상 URL
# @param pid 쓰레드의 아이디
# @return tempFilePath 임시파일의경로
# @return fileName 실제 파일의 이름
def getDocFile(self, url, pid):
logger.debug('HTTPMgr.getDocFile() start~!!')
# 0. URL을 검증한 뒤 파일이름만 분리한다.
url = self._validateUrl(url)
if url == None:
return None, None
urlPattern = url.split('/')
urlPattern.reverse()
fileName = urlPattern[0]
tempFilePath = None
tempFile = None
# 1. 파일을 Temp File Path ( 환경파일 tempFileRepository 위치) 에 저장한다.
try :
tempFile = tempfile.mkstemp( '_'+fileName, pid+'_', self.tempFileRepository)
os.close(tempFile[0])
tempFilePath, header = urllib.urlretrieve(url , tempFile[1])
if tempFilePath is not None and os.path.exists(tempFilePath) == True:
contentType = stringUtil.noneTrim( header.get('Content-Type'), '' )
# 1.1 다운로드받은 파일의 형식이 HTML일 경우 삭제
if contentType.find('text/html') != -1:
os.remove(tempFilePath)
tempFilePath = None
except IOError, msg:
msgStr = msg.__str__()
if os.path.exists(tempFile[1]) == True:
os.remove(tempFile[1])
tempFilePath = None
logger.debug('(' + pid + ') ' + ' : IOError - ' + msgStr )
except OSError, msg:
msgStr = msg.__str__()
if tempFile is not None and os.path.exists(tempFile[1]) == True:
os.remove(tempFile[1])
tempFilePath = None
logger.error('(' + pid + ') ' + ' : OSError - ' + msgStr)
except socket.timeout, msg:
msgStr = msg.__str__()
if os.path.exists(tempFile[1]) == True:
#os.close(tempFile[0])
urllib.urlcleanup()
try :
os.remove(tempFile[1])
except Exception, msg:
os.remove(tempFile[1])
print msg
logger.error('(' + pid + ') ' + ' : socket.timeout - ' + msgStr)
raise socket.timeout
except socket.error, msg:
msgStr = msg.__str__()
if os.path.exists(tempFile[1]) == True:
os.remove(tempFile[1])
tempFilePath = None
urllib.urlcleanup()
logger.error('(' + pid + ') ' + ' : socket.socket - ' + msgStr)
except :
logger.error('(' + pid + ') ' + ' : Unknown - ' + sys.exc_info().__str__())
raise
logger.debug('HTTPMgr.getDocFile() end~!!')
return tempFilePath, fileName
프로그램은
생산자(1)개 소비자(20)개로 돌아가고 있구요.
생산자가 파일의 URL을 받아오면 소비자가 이를 다운 받아 옵니다.
파일을 다운로드 받는 getDocFile메소드에 문제가 있나요~? -_-;;
정말 하다 하다 안되면 urlretrieve와 같은 기능을 하는 립을
새로 짜야 할 것 같군요..ㅜ.ㅜ
자체 리플..
urllib.py같은 경우...
exception handling이 몇몇 군데에서 불안 함을 찾았습니다.
특히 fp를 open한체로 exception이 일어났을때
close하지 않고 except를 raise하는 경우가 발생 했습니다. ^@^;;;
그리구 python은 파이썬 마을 쪽으로 오세욥 ^@^;;
THe World is just awesome~!!
http://susukang.tistory.com
댓글 달기