import asyncio import timeit from urllib.request import urlopen from concurrent.futures import ThreadPoolExecutor import threading # 실행 시작 시간 start =timeit.default_timer() # 서비스 방향이 비슷한 사이트로 실습권장(예 게시판 성 커뮤니티) urls = ['https://daum.net', 'https://naver.com', 'http://mlbpark.donga.com', 'https://tistory.com'] async def fetch(url, executor): # 실행 res = await loop.get_running_loop(executor, urlopen, url) # 결과 반환 return res.read()[0:5] 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__': # 루프 초기화 asyncio.run(main()) # 수행 시간 계산 duration = timeit.default_timer() - start # 총 실행 시간 print('Total Running Time :', duration) 여기에서 loop is not defined라고 나오네요 지금 파이선은 3.14버전을 쓰고있는데 저기 loop를 무엇으로 바꾸면 될지 모르겠어요
학습하다가 궁금증이 생겨 질문 남겨드립니다. 그런데 __le__ 하고 __ge__ 를 실무에서 사용할 때, 헷갈릴것같아서 __le__만 사용하는 경우도 있나요? # __le__ : 작거나 같다 # __ge__ : 크거나 같다 def __le__(self, x): print('Called >> __le__') if self._price <= x._price: return True else: return False def __ge__(self, x): print('Called >> __ge__') if self._price >= x._price: return True else: return False 이거를 그냥 def __le__(self, x): print('Called >> __le__') if self._price >= x._price: return True else: return False 이런식으로 중간에 부등호만 바꿔도 정상 작동은 하긴하던데,, 혹시 하나로 통일해서 사용한다면 문제점이 발생할 수 있나요?
안녕하세요 atom이 2022년 후로 서비스 종료를 해서 파이썬 입문 강의부터 중급 강의 또한 여태까지 vsc 로 진행하고 있었는데요 그럼 이번 "파이썬 기본 환경 설정 2-3" 강의는 안 들어도 되는건가요?? 추가로 이전 강의에 있던 가상환경 설정은 vsc에서 다 완료 하였습니다! 그럼 앞으로의 강의를 들을 때 문제가 발생할 일은 없는건지도 궁금합니다!
안녕하세요 강사님. chapter 07-01 실행 오류가 납니다. 아니콘다 설치한 파이썬 3.13.5이고 주피터에서 실행했습니다. 무슨 오류인지도 모르겠어요. 도와주세요. 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/'] # 동시 실행, urliopen 함수는 블록 IO임, 쓰레드로 사용해서 urlpen을 따로 사용해 준다면 asyncio에서 제어권을 넘기는 넘기는 방식으로 코딩 async def fetch(url, executor): # 쓰레드가 ulrs 리스크 겟수만큼 들어 옴 # 실행 res = await loop.run_in_executor(executor, urlopen, url) # 결과 반환 return res.read()[0:5] # 내용이 많아 짜름 [0:5] # def main(): # --> async # yield --> await # 함수 내 yield 사용은 Generator async def main(): # 쓰레드 풀 생성 executor = ThreadPoolExecutor(max_workers=None) # future 객체 모아 gather에서 실행 (중요) futures = [ asyncio.ensure_future(fetch(url, executor)) for url in urls # fetch가 갯수만큼 생성 ] # 결과 취합 rst = await asyncio.gether(*futures) # future가 끝날 때가지 기다려 줄거예요, 리스트이기 때문에 언패킹 print('Result : ', rst) # 자~ 위에 fetch함수 만들자 if __name__ == '__main__': ## 패턴이 있음 # 루프 초기화 loop = asyncio.get_event_loop() ## 제어권을 주고 받는 핑퐁 게임 하겠다는 것 # 작업 완료까지 대기 loop.run_until_complete(main()) # run을 complete까지,끝날 때까지 루프는 계속된다s # 수행 시간 계산 duration = timeit.default_timer() - start # 총 실행 시간 print('Total Running Time : ', duration) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[1], line 49 46 loop = asyncio.get_event_loop() 47 ## 제어권을 주고 받는 핑퐁 게임 하겠다는 것 48 # 작업 완료까지 대기 ---> 49 loop.run_until_complete(main()) # run을 complete까지,끝날 때까지 루프는 계속된다s 50 # 수행 시간 계산 51 duration = timeit.default_timer() - start File /opt/anaconda3/lib/python3.13/asyncio/base_events.py:701, in BaseEventLoop.run_until_complete(self, future) 690 """Run until the Future is done. 691 692 If the argument is a coroutine, it is wrapped in a Task. (...) 698 Return the Future's result, or raise its exception. 699 """ 700 self._check_closed() --> 701 self._check_running() 703 new_task = not futures.isfuture(future) 704 future = tasks.ensure_future(future, loop=self) File /opt/anaconda3/lib/python3.13/asyncio/base_events.py:637, in BaseEventLoop._check_running(self) 635 def _check_running(self): 636 if self.is_running(): ... 638 if events._get_running_loop() is not None: 639 raise RuntimeError( 640 'Cannot run the event loop while another loop is running') RuntimeError: This event loop is already running Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
안녕하세요 선생님! 제 맥북 사양인데요, 도커에서 지원하는 버전이 맞지 않아서 설치 자체가 안되서 이렇게 질문 남깁니다..! 물론 다운로드도 mac intel 버전으로 했는데 지원하는 버전이 아니더군요 ㅠㅠ.. 혹시 제가 놓친 부분이 있는건지 혹은 다른 방법이나 툴이 있을까요? 감사합니다
안녕하세요. 강사님. Chapter05-04 : sum_func의 합이 이중 출력됩니다.(합 1500이 두 번 출력) def perf_clock(func): # func가 free vatiable def perf_clocked(*args): # 함수 시작 시간 st = time.perf_counter() # 함수 실행 result = func(*args) # 함수 종료 시간 et = time.perf_counter() - st # 실행 함수명 name = func.__name__ # 함수 매개변수 arg_str = ', '.join(repr(arg) for arg in args) # 결과 출력 print('[%0.5fs] %s(%s) -> %r' % (et, name, arg_str, result)) return result return perf_clocked ---------------------------------------- Called None Decorator -> sum_func [0.00001s] sum_func(100, 200, 300, 400, 500) -> 1500 1500 아무리 봐도 이유를 모르겠습니다. 제가 작성한 코드 지우고 강사님이 제공한 코드로 실행해도 동일합니다.
안녕하세요. 프론트엔드 개발자에서 백엔드/풀스택 전향 중인 개발자입니다. 연휴때 해당 강의를 수강 하면서 한편으로 질문 드리고 싶어서 질문을 작성 하게 되었습니다. 혹시 사내에서도 AI 도구 활용이 늘어나서, 학습·업무에 어디까지 적용할지 기준을 잡고 싶습니다. AI 도구(Cursor/Claude 등) 활용 시 ‘효율적인 작업’과 ‘주의할 작업’을 각각 3~5개 정도로 예를 들어 주실 수 있을까요? 또한 권장하시는 최소 코드 검증 루틴이 있으신지도 궁금합니다. 읽어주셔서 감사합니다.
import time from concurrent import futures WORK_LIST = [1000000, 10000000, 100000000, 1000000000] def sum_number(n): return sum(range(1, n + 1)) def main(): start_time = time.time() futures_list = [] with futures.ThreadPoolExecutor() as excecutor: for work in WORK_LIST: future = excecutor.submit(sum_number, work) futures_list.append(future) print(f"Schduled Work: {work} | {future}") print() result = futures.wait(futures_list, timeout=5.0) print(result) end_time = time.time() - start_time print(f"Excecute Time: {end_time:.2f}s / Result: {result}") if __name__ == '__main__': main() 현재 문제점은 최종 출력 시간이 12초정도 걸리는데 중간에 5초 wait 후 print(result)가 호출되는 것이 아니라 12초 후에 아래 코드가 실행될 때 함께 실행되며 모두 정상적으로 finished returned int로 나옵니다. print(f"Excecute Time: {end_time:.2f}s / Result: {result}") 터미널 출력 결과: DoneAndNotDoneFutures(done={<Future at 0x2545b19e780 state=finished returned int>, <Future at 0x2545b123b10 state=finished returned int>, <Future at 0x2545b16f230 state=finished returned int>, <Future at 0x2545b123390 state=finished returned int>}, not_done=set()) Excecute Time: 11.80s / Result: DoneAndNotDoneFutures(done={<Future at 0x2545b19e780 state=finished returned int>, <Future at 0x2545b123b10 state=finished returned int>, <Future at 0x2545b16f230 state=finished returned int>, <Future at 0x2545b123390 state=finished returned int>}, not_done=set())
def closure_ex1(): # Free Variable # 클로저 영역 series = [] # 함수 밖에 선언된 변수임에도 불구하고, 함수 호출이 끝나도 사라지지않고 계속 유지됨 def averager(v): series.append(v) print("inner >> {} / {}" .format(series, len(series))) return sum(series) / len(series) return averager avg_closure1 = closure_ex1() !!!해당부분은 nonlocal 선언을 하지않았는데 어떻게 자유 변수로 설정이되는건가요?!!!