python fastapi add_exception_handler

时间: 2025-06-30 12:11:41 浏览: 8
在 FastAPI 应用中添加自定义异常处理器可以通过 `@app.exception_handler()` 装饰器实现,这一机制允许开发者捕获特定的异常并返回定制化的响应。例如,可以为 `HTTPException` 添加一个全局处理器,以统一处理所有由应用抛出的 HTTP 错误。 以下是一个示例,展示如何添加一个自定义异常处理器来捕获和处理 `HTTPException`: ```python from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): # 返回一个自定义的 JSON 响应,包含状态码和错误信息 return JSONResponse( status_code=exc.status_code, content={"error": exc.detail}, ) @app.get("/example") async def example_endpoint(): # 抛出一个 HTTP 异常 raise HTTPException(status_code=400, detail="Bad request") ``` 上述代码中,当 `/example` 端点被调用时,会抛出一个 `HTTPException`,其状态码为 400,错误信息为 "Bad request"。由于已经定义了针对 `HTTPException` 的异常处理器,该异常会被捕获,并通过 `JSONResponse` 返回一个格式化的 JSON 响应[^1]。 此外,还可以为非 HTTP 特定的异常(如自定义异常类)添加处理器。例如,定义一个名为 `CustomError` 的异常类,并为其添加一个处理器: ```python class CustomError(Exception): pass @app.exception_handler(CustomError) async def custom_error_handler(request, exc): return JSONResponse( status_code=500, content={"error": "Internal server error"}, ) @app.get("/custom-example") async def custom_example_endpoint(): # 抛出自定义异常 raise CustomError() ``` 在这个例子中,当 `/custom-example` 端点被调用时,会抛出一个 `CustomError` 异常。该异常会被 `custom_error_handler` 捕获,并返回一个状态码为 500 的 JSON 响应,内容为 "Internal server error"[^1]。 这种机制不仅提升了错误处理的一致性,还增强了用户体验,因为客户端可以接收到结构化且有意义的错误信息。 ### 相关问题 1. 如何在 FastAPI 中使用中间件进行请求拦截和处理? 2. 如何在 FastAPI 中实现 JWT 身份验证? 3. 如何限制 FastAPI 应用中的并发请求数量? 4. 如何在 FastAPI 中记录日志以便调试异常?
阅读全文

相关推荐

FO: Will watch for changes in these directories: ['E:\\python\\Python313\\fastapi\\ORM系统'] INFO: Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) INFO: Started reloader process [8364] using StatReload INFO: Started server process [12812] INFO: Waiting for application startup. INFO: Application startup complete. INFO: 127.0.0.1:63944 - "GET /docs HTTP/1.1" 200 OK INFO: 127.0.0.1:63944 - "GET /openapi.json HTTP/1.1" 200 OK INFO: 127.0.0.1:63944 - "GET /student/ HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "E:\python\Python313\fastapi\.venv\Lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 403, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ self.scope, self.receive, self.send ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 60, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\applications.py", line 1054, in __call__ await super().__call__(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\applications.py", line 112, in __call__ await self.middleware_stack(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\errors.py", line 187, in __call__ raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\errors.py", line 165, in __call__ await self.app(scope, receive, _send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\exceptions.py", line 62, in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 714, in __call__ await self.middleware_stack(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 734, in app await route.handle(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 288, in handle await self.app(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 76, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 73, in app response = await f(request) ^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\routing.py", line 301, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<3 lines>... ) ^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\routing.py", line 212, in run_endpoint_function return await dependant.call(**values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\ORM系统\api\students.py", line 26, in get_all_students stu1 = await Students.filter(sno__gt=2003) ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\models.py", line 1323, in filter return cls._meta.manager.get_queryset().filter(*args, **kwargs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\manager.py", line 19, in get_queryset return QuerySet(self._model) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\queryset.py", line 337, in __init__ super().__init__(model) ~~~~~~~~~~~~~~~~^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\queryset.py", line 99, in __init__ self.capabilities: Capabilities = model._meta.db.capabilities ^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\models.py", line 280, in db raise ConfigurationError( f"default_connection for the model {self._model} cannot be None" ) tortoise.exceptions.ConfigurationError: default_connection for the model <class 'ORM系统.models.Students'> cannot be None

安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows Traceback (most recent call last): File "C:\Users\yph\anaconda3\Lib\site-packages\conda\exception_handler.py", line 18, in __call__ return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\yph\anaconda3\Lib\site-packages\conda\cli\main.py", line 73, in main_sourced from ..base.context import context File "C:\Users\yph\anaconda3\Lib\site-packages\conda\base\context.py", line 47, in <module> from ..common.path import BIN_DIRECTORY, expand, paths_equal ModuleNotFoundError: No module named 'conda.common.path' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\yph\anaconda3\Scripts\conda-script.py", line 12, in <module> sys.exit(main()) ^^^^^^ File "C:\Users\yph\anaconda3\Lib\site-packages\conda\cli\main.py", line 105, in main return conda_exception_handler(main, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\yph\anaconda3\Lib\site-packages\conda\exception_handler.py", line 386, in conda_exception_handler return_value = exception_handler(func, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\yph\anaconda3\Lib\site-packages\conda\exception_handler.py", line 21, in __call__ return self.handle_exception(exc_val, exc_tb) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\yph\anaconda3\Lib\site-packages\conda\exception_handler.py", line 52, in handle_exception from .exceptions import ( File "C:\Users\yph\anaconda3\Lib\site-packages\conda\exceptions.py", line 17, in <module> from requests.exceptions import JSONDecodeError File "C:\Users\yph\anaconda3\Lib\site-packages\requests\__init__.py", line 164, in <module> from .api import delete, get, head, options, patch, post, put, request File "C:\Users\yph\anaconda3\Lib\site-packages\requests\api.py", line 11, in <module>

..which was originally created as op 'add_5', defined at: File "C:/Users/omen/anaconda3/opencv/LLIE/now_methods/RLCE_NET/main.py", line 125, in <module> tf.app.run() [elided 3 identical lines from previous traceback] File "C:/Users/omen/anaconda3/opencv/LLIE/now_methods/RLCE_NET/main.py", line 104, in main model = lowlight_enhance(sess) File "C:\Users\omen\anaconda3\opencv\LLIE\now_methods\RLCE_NET\model.py", line 108, in __init__ self.loss_Decom = 0.84 * color + 0.08 * l1 + 0.08 * ssimr File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 150, in error_handler return fn(*args, **kwargs) File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1466, in binary_op_wrapper return func(x, y, name=name) File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 150, in error_handler return fn(*args, **kwargs) File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\util\dispatch.py", line 1176, in op_dispatch_handler return dispatch_target(*args, **kwargs) File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1837, in _add_dispatch return gen_math_ops.add_v2(x, y, name=name) File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 504, in add_v2 _, _, _op, _outputs = _op_def_library._apply_op_helper( File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 795, in _apply_op_helper op = g._create_op_internal(op_type_name, inputs, dtypes=None, File "C:\Users\omen\anaconda3\envs\pytorch\lib\site-packages\tensorflow\python\framework\ops.py", line 3381, in _create_op_internal ret = Operation.from_node_def(

(base) PS D:\000毕业论文\new_lab1> conda clean --all -y # �� Traceback (most recent call last): File "C:\Users\86138\anaconda3\Lib\site-packages\conda\exception_handler.py", line 17, in __call__ return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\86138\anaconda3\Lib\site-packages\conda\cli\main.py", line 36, in main_subshell from ..base.context import context File "C:\Users\86138\anaconda3\Lib\site-packages\conda\base\context.py", line 33, in <module> from ..common._os.linux import linux_get_libc_version File "C:\Users\86138\anaconda3\Lib\site-packages\conda\common\_os\__init__.py", line 8, in <module> from .windows import get_free_space_on_windows as get_free_space File "C:\Users\86138\anaconda3\Lib\site-packages\conda\common\_os\windows.py", line 11, in <module> from ctypes import ( File "C:\Users\86138\anaconda3\Lib\ctypes\__init__.py", line 8, in <module> from _ctypes import Union, Structure, Array ImportError: DLL load failed while importing _ctypes: 找不到指定的模块。 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\86138\anaconda3\Scripts\conda-script.py", line 12, in <module> sys.exit(main()) ^^^^^^ File "C:\Users\86138\anaconda3\Lib\site-packages\conda\cli\main.py", line 109, in main return conda_exception_handler(main, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\86138\anaconda3\Lib\site-packages\conda\exception_handler.py", line 389, in conda_exception_handler return_value = exception_handler(func, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\86138\anaconda3\Lib\site-packages\conda\exception_handler.py", line 20, in __call__ return self.handle_exception(exc_val, exc_tb) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\86138\anaconda3\Lib\site-packages\conda\exception_handler.py", line 52, in handle_exception from .exceptions import ( from .models.channel import Channel File "C:\Users\86138\anaconda3\Lib\site-packages\conda\models\channel.py", line 25, in <module> from ..base.context import Context, context File "C:\Users\86138\anaconda3\Lib\site-packages\conda\base\context.py", line 33, in <module> from ..common._os.linux import linux_get_libc_version File "C:\Users\86138\anaconda3\Lib\site-packages\conda\common\_os\__init__.py", line 8, in <module> from .windows import get_free_space_on_windows as get_free_space File "C:\Users\86138\anaconda3\Lib\site-packages\conda\common\_os\windows.py", line 11, in <module> from ctypes import ( File "C:\Users\86138\anaconda3\Lib\ctypes\__init__.py", line 8, in <module> from _ctypes import Union, Structure, Array ImportError: DLL load failed while importing _ctypes: 找不到指定的模块。 是什么原因

============================= test session starts ============================= collecting ... collected 1 item test_Add.py::TestCourseAdd::test_add_course ======================== 1 failed in 105.13s (0:01:45) ======================== FAILED [100%] test_Add.py:18 (TestCourseAdd.test_add_course) self = <test_Add.TestCourseAdd testMethod=test_add_course> def test_add_course(self): # 登录操作 self.login_page.input_username("qdkovd41") self.login_page.input_password("123456") sleep(5) self.login_page.click_login_button() sleep(3) > self.add_page.click_course_manage() test_Add.py:27: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ..\Page\AddPage.py:9: in click_course_manage self.find_element(By.PARTIAL_LINK_TEXT,"a > li > 系统管理").click() ..\Page\BasePage.py:9: in find_element return self.driver.find_element(by, value) D:\python\python3.12.5\Lib\site-packages\selenium\webdriver\remote\webdriver.py:888: in find_element return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"] D:\python\python3.12.5\Lib\site-packages\selenium\webdriver\remote\webdriver.py:429: in execute self.error_handler.check_response(response) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x0000022F70B81940> response = {'status': 404, 'value': '{"value":{"error":"no such element","message":"no such element: Unable to locate element: {\...07FF70FBCC119]\\n\\tBaseThreadInitThunk [0x00007FFABFD0E8D7+23]\\n\\tRtlUserThreadStart [0x00007FFAC0BFBF2C+44]\\n"}}'} def check_response(self, response: Dict[str, Any]) -> None: """Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object.

[ERROR] 2025-07-07T14:01:11+0800 django.request.log:241 [log_response] Internal Server Error: /api/seeds Traceback (most recent call last): File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\asgiref\sync.py", line 518, in thread_handler raise exc_info[1] File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\asgiref\sync.py", line 518, in thread_handler raise exc_info[1] File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\asgiref\sync.py", line 468, in __call__ ret = await asyncio.shield(exec_coro) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\concurrent\futures\thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\asgiref\sync.py", line 522, in thread_handler return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\viewsets.py", line 124, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\code\LVHM-ReturnSeedingWall\apps\seeds\views.py", line 65, in list queryset = self.filter_queryset(self.get_queryset()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\rest_framework\generics.py", line 154, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django_filters\rest_framework\backends.py", line 72, in filter_queryset return filterset.qs ^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django_filters\filterset.py", line 250, in qs qs = self.filter_queryset(qs) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django_filters\filterset.py", line 233, in filter_queryset queryset = self.filters[name].filter(queryset, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django_filters\filters.py", line 834, in __call__ return self.method(qs, self.f.field_name, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\code\LVHM-ReturnSeedingWall\apps\seeds\filters.py", line 95, in filter_order_by return queryset.order_by(*order_by_clauses) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django\db\models\query.py", line 1659, in order_by obj.query.add_ordering(*field_names) File "C:\Users\tong.zhang\AppData\Local\anaconda3\envs\python311\Lib\site-packages\django\db\models\sql\query.py", line 2226, in add_ordering raise FieldError( django.core.exceptions.FieldError: Using an aggregate in order_by() without also including it in annotate() is not allowed: Sum(F(quantity)) [ERROR] 2025-07-07T14:01:11+0800 django.channels.server.runserver:181 [log_action] HTTP GET /api/seeds?order_by_fields=quantity_f&page=1&page_size=1 500 [0.13, 127.0.0.1:4384]

async def queue_item_execution(self): while True: Healthcheck.write_or_update(TimeToKill.AT_QUEUE_RUNNER_LOOP_START.value) if self.processmanager_state.queue_is_executing: requesthandler = await self.init_execution() if requesthandler and "Finished" != requesthandler: await self.task_execution(requesthandler) self.robot_not_ready_counter = 0 if requesthandler.test_successfull_finished else \ self.robot_not_ready_counter if "Finished" == requesthandler: self.log(logging.INFO, "Queue is finished") break else: self.log_flooding_protected(level=logging.INFO, msg="Queue is paused") await asyncio.sleep(5) async def fetch_rabbitmq(self): await self.connect() # Ensure we have a connection before starting while True: try: channel = await self.connection.channel() queue = await channel.declare_queue(self.get_route_key()) async with queue.iterator() as queue_iter: async for message in queue_iter: async with message.process(): await self.on_message(message) except Exception as e: self.log(logging.ERROR, f"Error consuming messages: {e}") await asyncio.sleep(5) # Wait before retrying # Attempt to reconnect if the connection is closed or broken if self.connection.is_closed: self.log(logging.INFO, "Connection closed, attempting to reconnect") await self.connect() finally: # Prevent tight looping in case of idle queue await asyncio.sleep(0.1) asyncio.ensure_future(queue_runner.queue_item_execution()) asyncio.ensure_future(comm_interface.fetch_rabbitmq()) def handle_sigterm(): loop.stop() logging.log(logging.INFO, "Received SIGTERM: Shutting down Processmanager..") processmanager_state.set_queue_offline() sys.exit(0) loop.add_signal_handler(signal.SIGTERM, handle_sigterm) loop.add_signal_handler(signal.SIGINT, handle_sigterm) print("State, Queue Runner and Comm Interface initialized, starting loops..", flush=True) loop.run_forever() 走到break之后怎么走

(base) PS E:\桌面\Python_demo\Python实战\淘宝> python -u "e:\桌面\Python_demo\Python实战\淘宝\1.py" Traceback (most recent call last): File "e:\桌面\Python_demo\Python实战\淘宝\1.py", line 19, in <module> driver = webdriver.Chrome(options=options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__ super().__init__( File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\chromium\webdriver.py", line 67, in __init__ super().__init__(command_executor=executor, options=options) File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\remote\webdriver.py", line 260, in __init__ self.start_session(capabilities) File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\remote\webdriver.py", line 357, in start_session response = self.execute(Command.NEW_SESSION, caps)["value"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\remote\webdriver.py", line 448, in execute self.error_handler.check_response(response) File "C:\Users\user\AppData\Roaming\Python\Python312\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: session not created: cannot connect to chrome at localhost:9222 from chrome not reachable

from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() # 设置远程调试端口号为9222 options.add_argument("--remote-debugging-port=9222") # 必须与debuggerAddress端口一致 options.debugger_address = "127.0.0.1:9222" # 显式指定连接地址 options.add_argument("--user-data-dir=C:/Users/fzh13/Desktop/selenium/cookie") options.add_argument('--start-maximized') service = webdriver.ChromeService(executable_path='chromedriver.exe') driver = webdriver.Chrome(service=service, options=options) try: # 打开目标网站 driver.get("https://www.csdn.net/") # 等待页面加载完成 time.sleep(5) finally: pass 运行后报错:Traceback (most recent call last): File "C:\Users\fzh13\Desktop\selenium\test.py", line 18, in <module> driver = webdriver.Chrome(service=service, options=options) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__ super().__init__( File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 66, in __init__ super().__init__(command_executor=executor, options=options) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 241, in __init__ self.start_session(capabilities) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 329, in start_session response = self.execute(Command.NEW_SESSION, caps)["value"] File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 384, in execute self.error_handler.check_response(response) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionN

启动程序报错libpng warning: iCCP: known incorrect sRGB profile libpng warning: iCCP: known incorrect sRGB profile libpng warning: iCCP: known incorrect sRGB profile libpng warning: iCCP: known incorrect sRGB profile libpng warning: iCCP: known incorrect sRGB profile Traceback (most recent call last): File "D:\2_stydy\python_study\pc\text.py", line 79, in <module> main() File "D:\2_stydy\python_study\pc\text.py", line 65, in main driver = login_xiaohongshu() ^^^^^^^^^^^^^^^^^^^ File "D:\2_stydy\python_study\pc\text.py", line 29, in login_xiaohongshu driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__ super().__init__( File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 66, in __init__ super().__init__(command_executor=executor, options=options) File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 250, in __init__ self.start_session(capabilities) File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 342, in start_session response = self.execute(Command.NEW_SESSION, caps)["value"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute self.error_handler.check_response(response) File "D:\2_stydy\python_study\pc\venv\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary Stacktrace: Backtrace: GetHandleVerifier [0x004

Traceback (most recent call last): File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\PIL\ImageFile.py", line 547, in _save fh = fp.fileno() AttributeError: '_idat' object has no attribute 'fileno' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Yxy\PycharmProjects\PythonProject\pytorch-CNN-SBATM-master\train.py", line 220, in <module> trainandsave() File "C:\Yxy\PycharmProjects\PythonProject\pytorch-CNN-SBATM-master\train.py", line 187, in trainandsave writer.add_image('aoteman', img_grid) # 将图像数据添加到summary,以供TensorBoard使用 File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\torch\utils\tensorboard\writer.py", line 625, in add_image image(tag, img_tensor, dataformats=dataformats), global_step, walltime File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\torch\utils\tensorboard\summary.py", line 577, in image image = make_image(tensor, rescale=rescale) File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\torch\utils\tensorboard\summary.py", line 630, in make_image image.save(output, format="PNG") File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\PIL\Image.py", line 2568, in save save_handler(self, fp, filename) File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\PIL\PngImagePlugin.py", line 1431, in _save ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)]) File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\PIL\ImageFile.py", line 551, in _save _encode_tile(im, fp, tile, bufsize, None, exc) File "C:\Yxy\Anaconda2\envs\pythorch_gpu\lib\site-packages\PIL\ImageFile.py", line 570, in _encode_tile errcode, data = encoder.encode(bufsize)[1:] KeyboardInterrupt在训练代码是这个提示是什么意思

大家在看

最新推荐

recommend-type

MATLAB统计工具箱中的回归分析命令PPT课件.ppt

MATLAB统计工具箱中的回归分析命令PPT课件.ppt
recommend-type

ASP.NET新闻管理系统:用户管理与内容发布功能

知识点: 1. ASP.NET 概念:ASP.NET 是一个开源、服务器端 Web 应用程序框架,用于构建现代 Web 应用程序。它是 .NET Framework 的一部分,允许开发者使用 .NET 语言(例如 C# 或 VB.NET)来编写网页和 Web 服务。 2. 新闻发布系统功能:新闻发布系统通常具备用户管理、新闻分级、编辑器处理、发布、修改、删除等功能。用户管理指的是系统对不同角色的用户进行权限分配,比如管理员和普通编辑。新闻分级可能是为了根据新闻的重要程度对它们进行分类。编辑器处理涉及到文章内容的编辑和排版,常见的编辑器有CKEditor、TinyMCE等。而发布、修改、删除功能则是新闻发布系统的基本操作。 3. .NET 2.0:.NET 2.0是微软发布的一个较早版本的.NET框架,它是构建应用程序的基础,提供了大量的库和类。它在当时被广泛使用,并支持了大量企业级应用的构建。 4. 文件结构分析:根据提供的压缩包子文件的文件名称列表,我们可以看到以下信息: - www.knowsky.com.txt:这可能是一个文本文件,包含着Knowsky网站的一些信息或者某个页面的具体内容。Knowsky可能是一个技术社区或者文档分享平台,用户可以通过这个链接获取更多关于动态网站制作的资料。 - 源码下载.txt:这同样是一个文本文件,顾名思义,它可能包含了一个新闻系统示例的源代码下载链接或指引。用户可以根据指引下载到该新闻发布系统的源代码,进行学习或进一步的定制开发。 - 动态网站制作指南.url:这个文件是一个URL快捷方式,它指向一个网页资源,该资源可能包含关于动态网站制作的教程、指南或者最佳实践,这对于理解动态网站的工作原理和开发技术将非常有帮助。 - LixyNews:LixyNews很可能是一个项目文件夹,里面包含新闻发布系统的源代码文件。通常,ASP.NET项目会包含多个文件,如.aspx文件(用户界面)、.cs文件(C#代码后台逻辑)、.aspx.cs文件(页面的代码后台)等。这个文件夹中应该还包含Web.config配置文件,它用于配置整个项目的运行参数和环境。 5. 编程语言和工具:ASP.NET主要是使用C#或者VB.NET这两种语言开发的。在该新闻发布系统中,开发者可以使用Visual Studio或其他兼容的IDE来编写、调试和部署网站。 6. 新闻分级和用户管理:新闻分级通常涉及到不同的栏目分类,分类可以是按照新闻类型(如国际、国内、娱乐等),也可以是按照新闻热度或重要性(如头条、焦点等)进行分级。用户管理则是指系统需具备不同的用户身份验证和权限控制机制,保证只有授权用户可以进行新闻的发布、修改和删除等操作。 7. 编辑器处理:一个新闻发布系统的核心组件之一是所使用的Web编辑器。这个编辑器可以是内置的简单文本框,也可以是富文本编辑器(WYSIWYG,即所见即所得编辑器),后者能够提供类似于Word的编辑体验,并能输出格式化后的HTML代码。CKEditor和TinyMCE是常用的开源Web编辑器,它们支持插入图片、视频、表格等多种媒体,并能对文本进行复杂的格式化操作。 8. 发布、修改和删除功能:这是新闻发布系统的基本操作功能。发布功能允许用户将编辑好的新闻内容上线;修改功能可以对已发布的新闻内容进行更新;删除功能则用于移除不再需要的新闻文章。这些操作通常需要后台管理界面来支持,并且系统会在数据库中记录相关操作的记录,以便管理历史版本和审计日志。 以上知识点覆盖了从ASP.NET基础、新闻发布系统的具体功能实现到系统开发过程中的细节处理等多个方面。开发者在构建类似系统时,需要深入了解这些知识点,才能设计和实现一个功能完备、易用、安全的新闻发布系统。
recommend-type

【实战派量化投资秘籍】:Pair Trading策略全方位解析

# 摘要 量化投资中的Pair Trading策略是一种依赖统计套利和市场效率假说的交易方法,其核心在于选择相关性高的资产作为交易对并应用协整理论进行市场中立投资。本文首先概述了Pair Trading策略的理论基础,随后详细探讨了策略的实操技巧,包括数据预处理、模型建立和交易信号生成。接着,文章重点介绍了策略的编程实现,提供了环境搭建
recommend-type

fpga中保持时间建立时间时序约束

<think>我们讨论的是FPGA中的建立时间(Setup Time)和保持时间(Hold Time)时序约束问题。建立时间是指在时钟有效边沿到来之前,数据必须保持稳定的最小时间。保持时间是指在时钟有效边沿到来之后,数据必须保持稳定的最小时间。时序约束就是确保设计满足这些时间要求。 在FPGA设计中,我们通过时序约束(如时钟约束、输入输出延迟约束等)来告知工具设计的时序要求,工具会根据这些约束进行优化和验证。 以下是关于建立时间和保持时间时序约束的详细说明: ### 1. 建立时间和保持时间的基本概念 - **建立时间(Setup Time)**:时钟边沿到达前,数据必须稳定的时间。 -
recommend-type

Notepad2: 高效替代XP系统记事本的多功能文本编辑器

### 知识点详解 #### 标题解析 - **Vista记事本(Notepad2)**: Vista记事本指的是一款名为Notepad2的文本编辑器,它不是Windows Vista系统自带的记事本,而是一个第三方软件,具备高级编辑功能,使得用户在编辑文本文件时拥有更多便利。 - **可以替换xp记事本Notepad**: 这里指的是Notepad2拥有替换Windows XP系统自带记事本(Notepad)的能力,意味着用户可以安装Notepad2来获取更强大的文本处理功能。 #### 描述解析 - **自定义语法高亮**: Notepad2支持自定义语法高亮显示,可以对编程语言如HTML, XML, CSS, JavaScript等进行关键字着色,从而提高代码的可读性。 - **支持多种编码互换**: 用户可以在不同的字符编码格式(如ANSI, Unicode, UTF-8)之间进行转换,确保文本文件在不同编码环境下均能正确显示和编辑。 - **无限书签功能**: Notepad2支持设置多个书签,用户可以根据需要对重要代码行或者文本行进行标记,方便快捷地进行定位。 - **空格和制表符的显示与转换**: 该编辑器可以将空格和制表符以不同颜色高亮显示,便于区分,并且可以将它们互相转换。 - **文本块操作**: 支持使用ALT键结合鼠标操作,进行文本的快速选择和编辑。 - **括号配对高亮显示**: 对于编程代码中的括号配对,Notepad2能够高亮显示,方便开发者查看代码结构。 - **自定义代码页和字符集**: 支持对代码页和字符集进行自定义,以提高对中文等多字节字符的支持。 - **标准正则表达式**: 提供了标准的正则表达式搜索和替换功能,增强了文本处理的灵活性。 - **半透明模式**: Notepad2支持半透明模式,这是一个具有视觉效果的功能,使得用户体验更加友好。 - **快速调整页面大小**: 用户可以快速放大或缩小编辑器窗口,而无需更改字体大小。 #### 替换系统记事本的方法 - **Windows XP/2000系统替换方法**: 首先关闭系统文件保护,然后删除系统文件夹中的notepad.exe,将Notepad2.exe重命名为notepad.exe,并将其复制到C:\Windows和C:\Windows\System32目录下,替换旧的记事本程序。 - **Windows 98系统替换方法**: 直接将重命名后的Notepad2.exe复制到C:\Windows和C:\Windows\System32目录下,替换旧的记事本程序。 #### 关闭系统文件保护的方法 - 通过修改Windows注册表中的"SFCDisable"键值,可以临时禁用Windows系统的文件保护功能。设置键值为"FFFFFF9D"则关闭文件保护,设置为"0"则重新启用。 #### 下载地址 - 提供了Notepad2的下载链接,用户可以通过该链接获取安装包。 #### 文件压缩包内文件名 - **Notepad2MOD1.1.0.8CN.exe**: 这是压缩包内所含的Notepad2编译版本,表明这是一个中文版的安装程序,版本号为1.1.0.8。 ### 总结 Notepad2是一款强大的文本编辑器,它继承了传统的记事本程序界面,同时引入了诸多增强功能,如语法高亮、编码格式转换、书签管理、文本操作快捷键、括号高亮匹配等。这使得它在处理代码、标记语言和其他文本文件时具备极大的优势。用户可以通过替换系统默认记事本的方式,将Notepad2融入到操作系统中,充分享受这些高级功能带来的便捷。同时,提供了关闭系统文件保护的方法,以便用户能够顺利完成替换工作。最后,给出了下载地址,方便用户获取软件安装包。
recommend-type

【mPower1203驱动故障全攻略】:排除新手疑难杂症,提升部署效率

# 1. mPower1203驱动概述与故障诊断基础 在当今信息技术飞速发展的时代,高效准确地诊断和解决驱动故障对于确保企业级IT系统的稳定运行至关重要。mPower1203驱动作为一个广泛应用于高性能计算和数据处理领域的驱动程序,它的稳定性和性能优化对于很多关键业务系统都是不可忽视的。本章节将为您提供一个mPower1203驱动的概述,并对故障诊断的
recommend-type

keil5打不开

<think>我们正在处理Keil 5无法打开的问题。根据引用资料,可能的原因和解决方案如下: 1. 工程路径过长:将工程移动到较短的路径下(如D:\Project)[^3]。 2. 需要安装C51支持包(如果涉及51单片机)[^2]。 3. 编译器配置问题:重新安装或添加ARM编译器[^4]。 4. 软件冲突:以管理员身份运行Keil,并确保安装路径正确。 下面详细说明解决方案:</think>### Keil 5无法打开的解决方法 根据引用资料,Keil 5无法打开通常有以下几种原因及解决方案: #### 1. **工程路径过长问题** [^3] 当工程文件路径嵌套过深时(
recommend-type

远程进程注入技术详解:DLL注入的实现步骤

标题中提到的"RemoteCall"是一种远程进程注入技术,其关键知识点围绕着如何在不直接操作目标进程的情况下,在远程进程内存空间中加载和执行代码。这一技术广泛应用于多个领域,包括但不限于恶意软件开发、安全测试、系统管理工具等。下面,我们将深入探讨这一技术的关键步骤以及涉及的相关技术概念。 ### 进程ID的获取 要对远程进程进行操作,首先需要知道该进程的标识符,即进程ID(Process Identifier,PID)。每个运行中的进程都会被操作系统分配一个唯一的进程ID。通过系统调用或使用各种操作系统提供的工具,如Windows的任务管理器或Linux的ps命令,可以获取到目标进程的PID。 ### 远程进程空间内存分配 进程的内存空间是独立的,一个进程不能直接操作另一个进程的内存空间。要注入代码,需要先在远程进程的内存空间中分配一块内存区域。这一操作通常通过调用操作系统提供的API函数来实现,比如在Windows平台下可以使用VirtualAllocEx函数来在远程进程空间内分配内存。 ### 写入DLL路径到远程内存 分配完内存后,接下来需要将要注入的动态链接库(Dynamic Link Library,DLL)的完整路径字符串写入到刚才分配的内存中。这一步是通过向远程进程的内存写入数据来完成的,同样需要使用到如WriteProcessMemory这样的API函数。 ### 获取Kernel32.dll中的LoadLibrary地址 Kernel32.dll是Windows操作系统中的一个基本的系统级动态链接库,其中包含了许多重要的API函数。LoadLibrary函数用于加载一个动态链接库模块到指定的进程。为了远程调用LoadLibrary函数,必须首先获取到这个函数在远程进程内存中的地址。这一过程涉及到模块句柄的获取和函数地址的解析,可以通过GetModuleHandle和GetProcAddress这两个API函数来完成。 ### 创建远程线程 在有了远程进程的PID、分配的内存地址、DLL文件路径以及LoadLibrary函数的地址后,最后一步是创建一个远程线程来加载DLL。这一步通过调用CreateRemoteThread函数来完成,该函数允许调用者指定一个线程函数地址和一个参数。在这里,线程函数地址就是LoadLibrary函数的地址,参数则是DLL文件的路径。当远程线程启动后,它将在目标进程中执行LoadLibrary函数,从而加载DLL,实现代码注入。 ### 远程进程注入的应用场景与风险 远程进程注入技术的应用场景十分广泛。在系统管理方面,它允许用户向运行中的应用程序添加功能,如插件支持、模块化更新等。在安全领域,安全工具会使用注入技术来提供深度防护或监控。然而,远程进程注入技术也具有极高的风险性,特别是当被用于恶意软件时,它能够被用来注入恶意代码,对用户系统的安全性和稳定性造成威胁。因此,了解这一技术的同时,也必须对其潜在的安全风险有所认识,特别是在进行系统安全防护时,需要对该技术进行检测和防护。 ### 结语 通过对"RemoteCall"远程线程注入技术的知识点分析,我们了解到这一技术的强大能力,以及它在安全测试、系统维护和潜在恶意软件开发中的双重作用。掌握远程进程注入技术不仅要求对操作系统和编程有深入了解,还要求具备应对潜在安全风险的能力。在未来,随着技术的发展和安全挑战的增加,对这类技术的掌握和应用将变得更加重要。
recommend-type

【驱动安装背后的故事】:mPower1203机制深度剖析及优化技巧

# 1. 驱动安装机制概述 ## 简介 驱动安装机制是指操作系统与计算机硬件设备之间交互的过程。这一过程涉及到驱动软件的识别、加载和初始化,确保硬件设备能够在操作系统中正确、高效地运行。本章节将从宏观角度对驱动安装机制进行概述,为深入探讨特定驱动如mPower1203提供基础。 ## 驱动安装的步骤 一
recommend-type

tensorflow2.5.0 linux-aarch64.whl

<think>我们正在寻找适用于Linux AArch64架构的TensorFlow 2.5.0的预编译wheel文件。根据引用[1]和[2],我们知道在AArch64架构上安装TensorFlow可以通过预编译的wheel文件(如果可用)或者从源码编译。但是,用户明确要求wheel文件下载。 然而,请注意: 1. 引用[1]提到从Github下载安装包:tensorflow-on-arm,但该仓库主要提供TensorFlow 1.x版本的预编译包,且文件名中明确有cp35(Python3.5)和aarch64。 2. 引用[2]提到在aarch64上编译安装TensorFlow1.1