Back to main.

Calmcode Shorts

watch logowatch

Installation

If you're on a mac the app should already be installed. Just in case though, you can install the tool via;

brew install watch

On many linux distributions it should also already be installed.

Usage

The watch command can be used to rerun an command on the command line so you can "watch" what the new output is. The syntax for running it is;

watch <whatever other cli command>

The most basic demo is to run it together with the date command.

watch date

The date command will print the current datetime, so by calling watch in front of it you should see it update.

Automate Requests

Another interesting use-case for watch is to automatically send requests to and endpoint as you're debugging. In this case we'll run send many requests to a FastAPI app. If you're unfamiliar with it, you may appreciate our FastAPI course.

Here's the app we'll use:

import json
import datetime as dt
from fastapi import FastAPI


app = FastAPI()

@app.get("/log/")
def log():
    print(json.dumps({'dt': str(dt.datetime.now()), "info": "this workz!"}))
    return {"alive": "yes"}

You can run the app via;

python -m uvicorn app:app

Once the app is running you can query it using the httpie command line app.

http get http://127.0.0.1:8000/log/

If you want to send many repeated requests, you can run:

watch http get http://127.0.0.1:8000/log/

If you want, you can also choose to change the interval. In the example below, we will ping the endpoint every 500ms.

watch --interval 0.5 http get http://127.0.0.1:8000/log/

There's plenty of other neat use-cases for watch that are worth exploring too. Just to name another example: ou can "watch" a folder by running a script every 2 seconds that checks if there's a new file.


Back to main.