如何向Piface Digital回调函数传递自定义参数?
Great question! The pifacedigitalio library doesn't explicitly cover passing custom arguments to input event callbacks in its official docs, but there are two simple, reliable ways to make this work—especially since your callback is an async function. Let's walk through them:
1. Use a Lambda Expression to Capture External Variables
Lambda functions are perfect for wrapping your async callback and passing in the extra websocket and path parameters. Since pifacedigitalio expects a synchronous callback, we also need to schedule the async function with asyncio.create_task to ensure it runs properly.
Here's how to adjust your code:
import asyncio import pifacedigitalio # Initialize Piface pifacedigitalio.init() listener = pifacedigitalio.InputEventListener() # Assume websocket and path are already available in your scope listener.register( 1, pifacedigitalio.IODIR_ON, lambda event: asyncio.create_task(self.sendEventPushed(websocket, path)) ) # Run the listener in a separate thread to avoid blocking your async event loop import threading threading.Thread(target=listener.activate, daemon=True).start()
2. Use functools.partial to Bind Arguments
If you prefer a more explicit approach, functools.partial lets you pre-bind your custom arguments to the callback function. Just like with the lambda method, you'll need to wrap the partial function in a lambda to trigger the async task:
import asyncio import functools import pifacedigitalio pifacedigitalio.init() listener = pifacedigitalio.InputEventListener() # Bind websocket and path to your async callback bound_callback = functools.partial(self.sendEventPushed, websocket, path) # Register the wrapped callback listener.register( 1, pifacedigitalio.IODIR_ON, lambda event: asyncio.create_task(bound_callback()) ) # Start the listener in a daemon thread import threading threading.Thread(target=listener.activate, daemon=True).start()
Key Notes to Keep in Mind
- Async Compatibility:
pifacedigitalio's event system runs synchronously, so you must useasyncio.create_task(orasyncio.run_coroutine_threadsafeif your listener is in a different thread) to execute your async callback without blocking. - Object Lifetime: Make sure
websocketandpathare still valid when the button is pressed—avoid situations where these objects are garbage-collected before the event triggers. - Thread Safety: Running the listener in a daemon thread prevents it from blocking your main async event loop, which is crucial for WebSocket applications.
内容的提问来源于stack exchange,提问作者Juliosor

