working on a main.py for a plugin here is my code is python read pipe blocking in any…
- User
working on a main.py for a plugin here is my code is python read pipe blocking in any way? if so how can i read the pipe differntly? #!/usr/bin/env python3 import os import logging import sys import subprocess import re import asyncio import decky_plugin import aiohttp from aiohttp import web from decky_plugin import DECKY_PLUGIN_DIR
Set up logging
logging.basicConfig(level=logging.DEBUG)
def camel_to_title(s): # Split the string into words using a regular expression words = re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z]|$)', s) # Convert the first character of each word to uppercase and join the words with spaces return ' '.join(word.capitalize() for word in words)
class Plugin: async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request)
PIPE_PATH = "/tmp/NSLGameScanner_pipe" if not os.path.exists(PIPE_PATH): decky_plugin.logger.error(f"Pipe file {PIPE_PATH} not found") return try: with open(PIPE_PATH, 'r') as pipe: while True: line = pipe.readline().strip() if not line: break print(f"Read from pipe: {line}") # print to console decky_plugin.logger.info(f"Read from pipe: {line}") # or log the line await ws.send_str(line) # send to WebSocket client except FileNotFoundError: decky_plugin.logger.error(f"Pipe file {PIPE_PATH} not found") except Exception as e: decky_plugin.logger.error(f"Error reading from pipe: {e}") return ws async def _unload(self): decky_plugin.logger.info("Goodbye World!") if self.site: await self.site.stop() decky_plugin.logger.info("Server stopped") # Log server stop await self.runner.cleanup() decky_plugin.logger.info("Server cleanup completed") # Log server cleanup # Migrations that should be performed before entering `_main()`. async def _migration(self): decky_plugin.logger.info("Migrating") # Initialize the web application and set up the WebSocket route self.app = web.Application() self.app.router.add_route('GET', '/ws', self.websocket_handler) self.runner = web.AppRunner(self.app) self.site = None # Set the command to run your bash script command = "/bin/bash -c 'curl -Ls https://raw.githubusercontent.com/moraroy/NonSteamLaunchers-On-Steam-Deck/main/NonSteamLaunchers.sh | nohup /bin/bash -s -- \"Decky Plugin\"'" # Log the command for debugging decky_plugin.logger.info(f"Running command: {command}") # Set up the environment for the new process env = os.environ.copy() env['DISPLAY'] = ':0' env['XAUTHORITY'] = os.path.join(os.environ['HOME'], '.Xauthority') process = subprocess.Popen(command, shell=True, env=env) # Wait for the script to complete and get the exit code exit_code = process.wait() # Log the exit code for debugging decky_plugin.logger.info(f"Command exit code: {exit_code}") if exit_code == 0: decky_plugin.logger.info("Migration successful") else: decky_plugin.logger.error("Migration failed") # Start the web server and pipe related code here decky_plugin.logger.info("Hello World!") await self.runner.setup() decky_plugin.logger.info("Server setup completed") # Log server setup self.site = web.TCPSite(self.runner, 'localhost', 8765) await self.site.start() decky_plugin.logger.info("Server started") # Log server start - Assistant
The code you provided does not include any code related to reading from a pipe. However, if you are referring to the
with open(PIPE_PATH, 'r') as pipe:line, it can potentially block if there is no data available in the pipe. This depends on the behavior of the operating system and how the pipe is being used.If you want to read from the pipe differently, you can consider using non-blocking I/O or asynchronous I/O. For example, you can use the
selectorpollfunctions to check if the pipe has data available before reading from it. Here is an example usingselect:import select with open(PIPE_PATH, 'r') as pipe: while True: # Use select to check if the pipe has data available readable, _, _ = select.select([pipe], [], [], 0) if readable: line = pipe.readline().strip() if not line: break print(f"Read from pipe: {line}") decky_plugin.logger.info(f"Read from pipe: {line}") await ws.send_str(line)Note that this is just an example and you may need to modify it based on your specific requirements and the behavior of the pipe you are working with.
- User
lets try poll
- Assistant
Sure, here's an example of using
pollto check if the pipe has data available before reading from it:import os import select PIPE_PATH = "/tmp/NSLGameScanner_pipe" if not os.path.exists(PIPE_PATH): decky_plugin.logger.error(f"Pipe file {PIPE_PATH} not found") return # Open the pipe in non-blocking mode pipe = os.open(PIPE_PATH, os.O_RDONLY | os.O_NONBLOCK) try: while True: # Use poll to check if the pipe has data available poll_obj = select.poll() poll_obj.register(pipe, select.POLLIN) # Wait for data to be available in the pipe events = poll_obj.poll(0) if not events: continue # Read from the pipe line = os.read(pipe, 4096).decode().strip() if not line: break print(f"Read from pipe: {line}") decky_plugin.logger.info(f"Read from pipe: {line}") await ws.send_str(line) finally: # Close the pipe os.close(pipe)This code opens the pipe in non-blocking mode () and uses to check if there is data available in the pipe before reading. If data is available, it reads from the pipe using . Note that the code includes a block to ensure that the pipe is closed properly, even if an exception occurs.
- User
im confused why does it need to open and close the pipe when im already doing that in the NSLGameScanner.py where the pipe is actually coming from?
- Assistant
Apologies for the confusion. If you are already opening and closing the pipe in the
NSLGameScanner.pyscript, then you don't need to do it again in themain.pyplugin script. You can simply refer to the pipe path and read from it directly.Here's an updated version of the code that removes the unnecessary
openandclosecalls on the pipe:PIPE_PATH = "/tmp/NSLGameScanner_pipe" if not os.path.exists(PIPE_PATH): decky_plugin.logger.error(f"Pipe file {PIPE_PATH} not found") return try: while True: with open(PIPE_PATH, 'r') as pipe: line = pipe.readline().strip() if not line: break print(f"Read from pipe: {line}") decky_plugin.logger.info(f"Read from pipe: {line}") await ws.send_str(line) except FileNotFoundError: decky_plugin.logger.error(f"Pipe file {PIPE_PATH} not found") except Exception as e: decky_plugin.logger.error(f"Error reading from pipe: {e}")