강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

kiminhong님의 프로필 이미지
kiminhong

작성한 질문수

AsyncIO & Beautifulsoup 관련 수업중 코딩 에러 문의 (파이썬 중급 chapter07_01, 02)

작성

·

325

0

안녕하세요,

인프런 중급 강의 마지막 수업을 VS Code 로 실행하는데 아래와 같은 에러가 있어서 문의 드립니다.

수업에서 알려주신대로 진행하였으며, 코딩을 처음부터 끝까지 다시 해보았는데도 같은 에러가 나서요. 제가 뭔가 잘 못한 것 같은데 이유를 모르겠습니다 ㅜㅜ. 저렇게 결과값을 도출할 수 없으니 Beautifulsoup 예제도 적용이 안되구요.

답변을 위해 더 필요한 내용이 있으시면 알려주세요.

 

감사합니다.

import asyncio
import timeit
from urllib.request import urlopen
from concurrent.futures import ThreadPoolExecutor
import threading

# 실행 시작 시간
start = timeit.default_timer()

# 서비스 방향이 비슷한 사이트로 실습 권장(예: 게시판성 커뮤니티)
urls = ['http://daum.net', 'https://naver.com', 'http://mlbpark.donga.com', 'https://tistory.com', 'https://wemakeprice.com/']

async def fetch(url,executor):
    # 실행
    res = await loop.run_in_executor(executor, urlopen, url)

    # 결과 반환
    return res.read()

async def main():
    # 스레드 풀 생성
    executor = ThreadPoolExecutor(max_workers=10)

    # future 객체 모아서 gather 에서 실행
    futures = [
        asyncio.ensure_future(fetch(url, executor)) for url in urls
    ]

    # 결과 취합
    rst = await asyncio.gather(*futures)

    print()
    print('Result : ', rst)


if __name__ == '__main__':
    # 루프 초기화
    loop == asyncio.get_event_loop()
    # 작업 완료까지 대기
    loop.run_until_complete(main())
    # 수행 시간 계산
    duration = timeit.default_timer() - start
    # 총 실행 시간
    print('Total Running Time : ', duration)

답변 1

0

안녕하세요, 인프런 AI 인턴이에요.

에러 메시지가 없이 짤린 코드를 보내주셨는데, async def main(): 함수가 중간에 끊겨서 짤린 것처럼 보입니다. 코딩도 처음부터 끝까지 다시 해보셨는데도 같은 에러가 발생한다니 어려운 상황일 것 같습니다. 혹시 VS Code에서 실행할 때, Python 인터프리터 설정 등을 다시 확인해보시는 것은 어떨까요? VS Code는 기존 프로젝트 설정을 그대로 가져온다는 점을 잊어버리시면 안 됩니다.

만약 설정 확인 후에도 이 에러가 지속되신다면, async def main(): 함수 뒤에 다른 코드 등이 더 남아있을 수 있습니다. 그런 경우엔 꼼꼼하게 다시 확인해보시거나 해당 부분의 코드를 보내주시면 더 도움이 될 것 같습니다.

kiminhong님의 프로필 이미지
kiminhong
질문자

안녕하세요,

수업에서 사용한 코딩은 모두 복사하여 보내드렸는데, async def main(): 함수가 끊겨서 짤린 것처럼 보이나요? 그리고 제가 설명을 앞에서 잘 못한 것 같아서.. 아래 코딩을 다 한 후 ctrl + F5을 눌렀는데 VS Code의 터미널에서 결과값을 도출해내지 못했습니다. 그리고는 problems 에 저렇게 3개의 문제가 있다고 떠서요.

import asyncio
import timeit
from urllib.request import urlopen
from concurrent.futures import ThreadPoolExecutor
import threading

# 실행 시작 시간
start = timeit.default_timer()

# 서비스 방향이 비슷한 사이트로 실습 권장(예: 게시판성 커뮤니티)
urls = ['http://daum.net', 'https://naver.com', 'http://mlbpark.donga.com', 'https://tistory.com', 'https://wemakeprice.com/']

async def fetch(url,executor):
    # 실행
    res = await loop.run_in_executor(executor, urlopen, url)

    # 결과 반환
    return res.read()

async def main():
    # 스레드 풀 생성
    executor = ThreadPoolExecutor(max_workers=10)

    # future 객체 모아서 gather 에서 실행
    futures = [
        asyncio.ensure_future(fetch(url, executor)) for url in urls
    ]

    # 결과 취합
    rst = await asyncio.gather(*futures)

    print()
    print('Result : ', rst)


if __name__ == '__main__':
    # 루프 초기화
    loop == asyncio.get_event_loop()
    # 작업 완료까지 대기
    loop.run_until_complete(main())
    # 수행 시간 계산
    duration = timeit.default_timer() - start
    # 총 실행 시간
    print('Total Running Time : ', duration)

 

kiminhong님의 프로필 이미지
kiminhong

작성한 질문수

질문하기