MCPcopy Create free account
hub / github.com/Louisym/MiniCC / lesson_4_timeout

Function lesson_4_timeout

tutorials/17_async_await_for_sse.py:244–287  ·  view source on GitHub ↗

Claude Code 的超时控制 (bash.rs:109-130) 用的就是这个模式。

()

Source from the content-addressed store, hash-verified

242# ============================================================
243
244def lesson_4_timeout():
245 """
246 Claude Code 的超时控制 (bash.rs:109-130) 用的就是这个模式。
247 """
248 print("\n" + "=" * 60)
249 print("第四课: 超时控制")
250 print("=" * 60)
251
252 async def slow_operation():
253 """一个很慢的操作"""
254 await asyncio.sleep(10) # 10 秒
255 return "完成"
256
257 async def demo_timeout():
258 # 给慢操作设置 0.5 秒超时
259 try:
260 result = await asyncio.wait_for(
261 slow_operation(),
262 timeout=0.5,
263 )
264 print(f" 成功: {result}")
265 except asyncio.TimeoutError:
266 print(f" 超时! 操作在 0.5s 后被取消")
267
268 print("\n 等待一个 10s 的操作,但超时设为 0.5s:")
269 asyncio.run(demo_timeout())
270
271 # Claude Code 的 send_with_retry 超时模式
272 print("\n 在 Claude Code 中的应用:")
273 print("""
274 # bash.rs 中的超时控制 (简化的 Python 版)
275 async def execute_with_timeout(command, timeout_ms):
276 try:
277 result = await asyncio.wait_for(
278 run_command(command),
279 timeout=timeout_ms / 1000,
280 )
281 return BashOutput(stdout=result, interrupted=False)
282 except asyncio.TimeoutError:
283 return BashOutput(
284 stderr=f"Command exceeded timeout of {timeout_ms} ms",
285 interrupted=True,
286 )
287 """)
288
289
290# ============================================================

Callers 1

Calls 2

demo_timeoutFunction · 0.85
runMethod · 0.80

Tested by

no test coverage detected