76 — Network: polling a server
Programs that watch a server keep asking it for the latest state. This is called polling. The loop is simple: fetch, show, wait, repeat — and stop when the server says it is done.
Steps
Create
status.jsonwith a state that a worker will change:
run it →{"status": "working", "step": 1}Serve the folder, as in guide 55:
python3 -m http.server 8000Fetching the status is the same
urlopencall as guide 55:
run it →from urllib.request import urlopen from json import loads url = "http://localhost:8000/status.json" status = loads(urlopen(url).read().decode("utf-8"))The full program polls in a loop, reports each state, and stops when the server reports
"done". Savepoll.nme:
run it →# poll.nme — watch status.json until it says done. # Run: nme r poll # Serve this folder first: python3 -m http.server 8000 # Change status.json to {"status": "done", "step": 2} while it runs. from urllib.request import urlopen from json import loads from time import sleep url = "http://localhost:8000/status.json" while True: status = loads(urlopen(url).read().decode("utf-8")) show f"step {status['step']}: {status['status']}" if status["status"] == "done": show "worker finished" break sleep(1)Each loop fetches the current file, prints it, and waits one second. To see the change, edit
status.json(the HTTP server re-reads the file on every request) and watch the program report the new step before stopping.Run it, then edit
status.jsonwhile it runs:nme r pollstep 1: working step 2: done worker finished
Try it yourself
Add a started timestamp to status.json and report how many seconds the
worker ran, or poll two endpoints and report when either one finishes.
What you learned
- Polling means fetching the latest state in a loop with a wait between tries.
- The HTTP server re-reads the file on every request, so edits appear live.
- A sentinel value like
"done"tells the loop when to stop. time.sleepcontrols how often the program asks.