im working on a project here is my main.py #!/usr/bin/env python3 import os import…
- User
im working on a project here is my main.py #!/usr/bin/env python3 import os import logging import sys import subprocess import re import json 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: # Asyncio-compatible long-running code, executed in a task when the plugin is loaded async def _main(self): decky_plugin.logger.info("Hello World!") PIPE_PATH = "/tmp/NSLGameScanner_pipe"
async def read_pipe(self, request): if not os.path.exists(self.PIPE_PATH): print(f"Pipe file {self.PIPE_PATH} not found") raise web.HTTPNotFound(text=f"Pipe file {self.PIPE_PATH} not found") pipe_fd = os.open(self.PIPE_PATH, os.O_RDONLY | os.O_NONBLOCK) data = [] while True: try: line = os.read(pipe_fd, 1024) except BlockingIOError: await asyncio.sleep(0.1) # No data, sleep and try again else: if line: line = line.decode().strip() print(f"Read from pipe: {line}") # print to console data.append(json.loads(line)) # Add the JSON data to the list else: break # End of file os.close(pipe_fd) return web.json_response(data) # Return the data as a JSON response 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 route self.app = web.Application() self.app.router.add_get('/data', self.read_pipe) 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
It looks like you are working on a project and have written the main.py file. However, there are a few points that I would like to mention:
-
The
async def _main(self)function does not seem to be called in the code provided. You might want to call it somewhere to execute the code inside. -
There is an issue with the
PIPE_PATHvariable. It is defined inside the_mainfunction, but it is used outside in theread_pipefunction. You may want to move thePIPE_PATHdefinition outside the_mainfunction so that it is accessible in other functions as well. -
The
self.PIPE_PATHvariable is accessed asPIPE_PATHin theread_pipefunction. You should update it toself.PIPE_PATHto access the correct variable. -
There is a mix of print statements and logging statements in the code. It is recommended to use logging consistently throughout the code for better log management.
-
The
web.json_response(data)statement in theread_pipefunction might throw an error ifdatais empty. You might want to handle this case separately to avoid any potential issues. -
There is a duplicate logging statement "Hello World!" right after the migration code. You may want to remove the duplicate statement.
I hope these suggestions help you with your project. Let me know if you have any further questions!
-
- User
here is my log....is this because of the web.json repsonse is empty? [2024-02-15 01:39:30,781][INFO]: Migrating [2024-02-15 01:39:30,782][INFO]: Running command: /bin/bash -c 'curl -Ls https://raw.githubusercontent.com/moraroy/NonSteamLaunchers-On-Steam-Deck/main/NonSteamLaunchers.sh | nohup /bin/bash -s -- "Decky Plugin"' [2024-02-15 01:39:36,538][INFO]: Command exit code: 0 [2024-02-15 01:39:36,538][INFO]: Migration successful [2024-02-15 01:39:36,538][INFO]: Hello World! [2024-02-15 01:39:36,539][INFO]: Server setup completed [2024-02-15 01:39:36,545][INFO]: Server started [2024-02-15 01:39:36,545][INFO]: Hello World! [2024-02-15 01:41:12,838][ERROR]: Error handling request Traceback (most recent call last): File "aiohttp/web_protocol.py", line 452, in _handle_request File "aiohttp/web_app.py", line 543, in _handle TypeError: Plugin.read_pipe() missing 1 required positional argument: 'request' [2024-02-15 01:41:12,841][INFO]: ::1 [15/Feb/2024:01:41:12 -0800] "GET /data HTTP/1.1" 500 245 "-" "Mozilla/5.0 (X11; Linux x86_64; Valve Steam Client/default/1705108172) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" [2024-02-15 01:41:19,570][INFO]: install was called [2024-02-15 01:41:19,570][INFO]: selected_options: {'epicGames': False, 'gogGalaxy': False, 'origin': False, 'uplay': False, 'battleNet': False, 'amazonGames': False, 'eaApp': False, 'legacyGames': False, 'itchIo': False, 'humbleGames': False, 'indieGala': False, 'rockstar': False, 'glyph': False, 'minecraft': False, 'psPlus': False, 'dmm': False, 'xboxGamePass': False, 'geforceNow': False, 'amazonLuna': False, 'netflix': False, 'hulu': False, 'disneyPlus': False, 'amazonPrimeVideo': False, 'youtube': False, 'twitch': True} [2024-02-15 01:41:19,571][INFO]: custom_websites: [] [2024-02-15 01:41:19,571][INFO]: separate_app_ids: False [2024-02-15 01:41:19,571][INFO]: start_fresh: False [2024-02-15 01:41:19,571][INFO]: stop_game_scanner: False [2024-02-15 01:41:19,571][INFO]: selected_options_list: ['"Twitch"'] [2024-02-15 01:41:19,574][INFO]: Running command: /bin/bash -c 'curl -Ls https://raw.githubusercontent.com/moraroy/NonSteamLaunchers-On-Steam-Deck/main/NonSteamLaunchers.sh | nohup /bin/bash -s -- "Twitch"'
- Assistant
Yes, the error is indeed related to the
read_pipefunction missing the required positional argumentrequest. In theasync def read_pipe(self, request)function definition,requestis the argument that represents the HTTP request being made to the server. However, in the traceback, it shows that the function was called without providing therequestargument.To fix this error, you need to make sure that when the
/dataroute is accessed, theread_pipefunction is called with therequestargument. This can be done by defining a route handler or callback function and passing it as the second argument toself.app.router.add_get('/data', self.read_pipe). For example:async def handle_data_request(request): plugin = Plugin() # Create an instance of the Plugin class return await plugin.read_pipe(request) # Call the read_pipe function with the request argument # Inside the _migration method self.app.router.add_get('/data', handle_data_request)With this change, the
handle_data_requestfunction will be called whenever the/dataroute is accessed, and it will call theread_pipefunction with therequestargument.I hope this helps! Let me know if you have further questions.
- User
does this look better? #!/usr/bin/env python3 import os import logging import sys import subprocess import re import json 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: # Asyncio-compatible long-running code, executed in a task when the plugin is loaded async def _main(self): decky_plugin.logger.info("Hello World!") PIPE_PATH = "/tmp/NSLGameScanner_pipe"
async def read_pipe(self, request): if not os.path.exists(self.PIPE_PATH): print(f"Pipe file {self.PIPE_PATH} not found") raise web.HTTPNotFound(text=f"Pipe file {self.PIPE_PATH} not found") pipe_fd = os.open(self.PIPE_PATH, os.O_RDONLY | os.O_NONBLOCK) data = [] while True: try: line = os.read(pipe_fd, 1024) except BlockingIOError: await asyncio.sleep(0.1) # No data, sleep and try again else: if line: line = line.decode().strip() print(f"Read from pipe: {line}") # print to console data.append(json.loads(line)) # Add the JSON data to the list else: break # End of file os.close(pipe_fd) return web.json_response(data) # Return the data as a JSON response async def handle_data_request(request): plugin = Plugin() # Create an instance of the Plugin class return await plugin.read_pipe(request) # Call the read_pipe function with the request argument 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 route self.app = web.Application() self.app.router.add_get(‘/data’, handle_data_request) 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
Yes, the code looks better now. The changes you made to define the
handle_data_requestfunction separately and pass it toself.app.router.add_get('/data', handle_data_request)are correct. This will ensure that thehandle_data_requestfunction is called when the/dataroute is accessed.Here is the updated code for reference:
async def handle_data_request(request): plugin = Plugin() # Create an instance of the Plugin class return await plugin.read_pipe(request) # Call the read_pipe function with the request argument class Plugin: # ... async def _migration(self): # ... self.app = web.Application() self.app.router.add_get('/data', handle_data_request) # Use the handle_data_request function as the route handler self.runner = web.AppRunner(self.app) self.site = None # ...With this change, the
handle_data_requestfunction will be called whenever the/dataroute is accessed, and it will call theread_pipefunction with therequestargument.I hope this helps! Let me know if you have any further questions.
- User
logically does it make sense can you tell me in laymans terms how this will work?
- Assistant
Certainly! In layman's terms, here's how the updated code works:
- When the program starts, it begins executing the
_migrationmethod, which performs necessary setup tasks. - Inside the
_migrationmethod, it initializes a web application and sets up a route for the/dataendpoint. This means that when a request is made to the/dataURL, the application will execute a specific function to handle that request. - The specific function that handles the
/datarequest is calledhandle_data_request. It creates an instance of thePluginclass and calls itsread_pipemethod, passing the request object as an argument. - The
read_pipemethod reads data from a named pipe, converts it to JSON format, and adds it to a list. - Once all the data has been read from the named pipe, the
read_pipemethod responds to the request with a JSON response containing the collected data. - After setting up the application and the route, the program starts a web server to listen for incoming requests.
- The web server runs in the background and waits for requests to the specified URL (in this case,
/data). - When a request is received at the
/dataURL, the web server calls thehandle_data_requestfunction, which in turn calls theread_pipefunction of thePluginclass to process the request and fetch the data. - The
read_pipefunction reads data from the named pipe and responds with the collected data as a JSON response. - The web server sends this response back to the client that made the request.
In summary, the code sets up a web server that listens for requests at the
/dataURL. When a request is received, it processes the request by reading data from a named pipe and responds with the collected data in JSON format.I hope this explanation helps! Let me know if you have any further questions.
- When the program starts, it begins executing the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.