brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m random picks a winner, a number or a dice roll from the terminal

Terminal
~/tips/tip-python-m-random-cli

python3 -m random pizza sushi pasta "leftovers again"

Picks a random word, whole number or decimal straight from the terminal, no script needed.

Who does the dishes tonight, or which of four branch names to keep: some decisions deserve a coin flip. Python 3.13 gave the random module a small command-line interface, so you can let the computer pick without writing a single line of code.

Give it a few words and it picks one:

python3 -m random pizza sushi pasta "leftovers again"

The module guesses what you want from the input. Several words or a string means a random choice, a whole number such as 6 means a random integer from 1 to 6 (both ends included), and a decimal number such as 1.5 gives a float between 0 and 1.5. If you’d rather not rely on the guessing, the explicit flags do the same thing:

python3 -m random --choice alice bob carol dave
python3 -m random --integer 20
python3 -m random --float 2.5

The short forms are -c, -i and -f. --integer 20 is a d20 roll, which I find a lot more fun than it has any right to be. The argument is the upper limit, and the lower one is always 1 for integers and 0 for floats.

It also slots nicely into a shell script. Something like sleep "$(python3 -m random --integer 30)" adds a random delay of up to 30 seconds before a job runs, so a few scripts don’t all hit the same server at the exact same moment.

Two caveats. You need Python 3.13 or newer. On an older version, python3 -m random runs the module’s old self-test instead and prints a page of timing statistics, which is confusing the first time you see it. Check with python3 --version first. And the Python docs are clear that random must not be used for anything security related. It’s fine for dinner and dice. For passwords and tokens, use the secrets module or a proper password generator.

Further reading: Python docs: random, command-line usage

More Terminal tips ioreg -rn AppleSmartBattery | grep CycleCount Terminal can save your windows and tabs as a window group Export a Terminal profile to a .terminal file and import it on another Mac mc hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}' All Terminal tips (116) All topics

Link