Take on the role of an experienced python coder. Write code as a daemon to read the…
- User
Take on the role of an experienced python coder. Write code as a daemon to read the power and temperature from an Nvidia GPU and expose it as a REST API in a web app.
Assistant
To create a daemon that reads power and temperature from an Nvidia GPU and exposes it as a REST API in a web app, we'll use the
nvidia-smicommand-line utility and theflaskframework in Python.First, install the required packages using pip:
pip install flaskNow, let's create the Python code for the daemon:
import psutil import subprocess import time from flask import Flask, jsonify app = Flask(__name__) def get_gpu_info(): output = subprocess.check_output("nvidia-smi --query-gpu=index,power.draw,temperature.gpu --format=csv,noheader", shell=True) output_split = output.decode('utf-8').split('\n') gpu_info = [] for line in output_split: if line: info = line.split(',') gpu_info.append({'index': int(info[0]), 'power_draw': float(info[1].strip()), 'temperature_gpu': float(info[2].strip())}) return gpu_info @app.route('/gpu_info') def gpu_info(): info = get_gpu_info() return jsonify(info) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)This code does the following:
- Imports required modules.
- Defines a Flask app.
- Defines a function
get_gpu_info()to read power and temperature data from the Nvidia GPU using thenvidia-smicommand and return it as a list of dictionaries. - Defines a route
/gpu_infofor the Flask app to expose the GPU information as a JSON response. - Starts the Flask app on
0.0.0.0:5000.
To run the script, save it as
app.pyand execute it:python app.pyNow, you can access the GPU information via the REST API by visiting http://localhost:5000/gpu_info in your web browser or sending a GET request to that URL using a tool like
curlorrequestsin Python.Keep in mind that this is a simple example and may not be suitable for production use. It's recommended to add error handling, logging, and performance optimizations as needed.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.