Skip to content

Instantly share code, notes, and snippets.

@kwsp
Last active March 23, 2021 14:06
Show Gist options
  • Save kwsp/dbf88d86b33a0521cc15229d133d4e0f to your computer and use it in GitHub Desktop.
Save kwsp/dbf88d86b33a0521cc15229d133d4e0f to your computer and use it in GitHub Desktop.
nvidia-smi in the browser, useful for monitoring a remote GPU server
import asyncio
import subprocess
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
def nvidia_smi():
try:
msg = subprocess.run(
["nvidia-smi"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5,
).stdout.decode()
except FileNotFoundError:
msg = "nvidia not available"
return msg
app = FastAPI()
html = """
<!DOCTYPE html>
<title>GPU Mon</title>
<style>* {font-family: monospace; white-space: pre-wrap;}</style>
<div id='message'></div>
<script>
var ws = new WebSocket("ws://" + window.location.host + "/gpu_mon/ws")
ws.onmessage = function(event) {
var message_el = document.getElementById('message')
message.innerHTML = event.data
}
</script>
"""
@app.get("/gpu_mon")
async def get():
return HTMLResponse(html)
@app.websocket("/gpu_mon/ws")
async def ws(websocket: WebSocket):
await websocket.accept()
while True:
await websocket.send_text(nvidia_smi())
await asyncio.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment