One-liners

Contents

One-liners#

Each entry is a python -c '...' command the operator can paste straight into a shell. Quoting uses single quotes around the program so embedded "..." strings need no escape; switch to double quotes when the program contains a literal apostrophe.

Print the Python version.

$ python -c 'import sys; print(sys.version)'

Dedupe a comma-separated list while preserving order.

$ python -c 'xs="a,b,a,c,b".split(","); print(list(dict.fromkeys(xs)))'

Dedupe a list when order does not matter.

$ python -c 'xs=[1,2,2,3,1]; print(sorted(set(xs)))'

Flatten one level of nesting.

$ python -c 'm=[[1,2],[3,4],[5,6]]; print([x for row in m for x in row])'

Invert a dict (values become keys).

$ python -c 'd={"a":1,"b":2}; print({v:k for k,v in d.items()})'

Group a list of (key, value) pairs into a dict-of-lists.

$ python -c '
from collections import defaultdict
pairs=[("a",1),("b",2),("a",3)]
g=defaultdict(list)
for k,v in pairs: g[k].append(v)
print(dict(g))'

Count word occurrences with Counter.

$ echo "the rain in spain stays in the plain" \
    | python -c 'import sys; from collections import Counter; print(Counter(sys.stdin.read().split()))'

Top-N frequencies.

$ python -c '
from collections import Counter
print(Counter("operator").most_common(3))'

Filter and double the even numbers from a range.

$ python -c 'print([x*2 for x in range(10) if x%2==0])'

Default a value with or when the source is falsy.

$ python -c 'import os; print(os.environ.get("PORT") or 8080)'

Conditional expression (ternary).

$ python -c 'n=7; print("even" if n%2==0 else "odd")'

Walrus to read-and-test stdin in one expression.

$ python -c '
import sys
while (chunk := sys.stdin.buffer.read(4096)):
    sys.stdout.buffer.write(chunk)' < input.bin > output.bin

Walrus inside a comprehension to capture every regex match.

$ python -c '
import re, sys
pat=re.compile(r"\b\d+\b")
print([m.group() for line in sys.stdin if (m := pat.search(line))])' < log.txt

Sum of squares with a generator expression.

$ python -c 'print(sum(x*x for x in range(10)))'

any over a stream; exits 0 when any input line starts with ERROR.

$ python -c '
import sys
sys.exit(0 if any(line.startswith("ERROR") for line in sys.stdin) else 1)' < app.log

Slice a string into fixed-size chunks.

$ python -c 's="abcdefghij"; n=3; print([s[i:i+n] for i in range(0,len(s),n)])'

Reverse a string.

$ python -c 'print("operator"[::-1])'

Read a whole text file in one expression.

$ python -c 'import pathlib; print(pathlib.Path("/etc/hostname").read_text().strip())'

Pretty-print a JSON file.

$ python -c 'import json,sys; print(json.dumps(json.load(sys.stdin), indent=2, sort_keys=True))' < raw.json

Write a JSON file in one expression.

$ python -c '
import json, pathlib
pathlib.Path("out.json").write_text(json.dumps({"ok": True}, indent=2))'

Hash a file with SHA-256.

$ python -c 'import hashlib,pathlib,sys; print(hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest())' payload.bin

Sort lines on the second TAB-separated column, numeric.

$ python -c '
import sys
for line in sorted(sys.stdin, key=lambda r: int(r.split("\t")[1])):
    sys.stdout.write(line)' < data.tsv

Build a dict from two parallel comma lists.

$ python -c 'k="a,b,c".split(","); v="1,2,3".split(","); print(dict(zip(k,v)))'

Zip and unzip a list of pairs.

$ python -c '
pairs=[("alice",30),("bob",25)]
names, ages = zip(*pairs)
print(names, ages)'

TCP port probe (exit 0 = open, 1 = closed).

$ python -c '
import socket, sys
host, port = sys.argv[1], int(sys.argv[2])
try:
    with socket.create_connection((host, port), timeout=2):
        sys.exit(0)
except OSError:
    sys.exit(1)' example.com 443

Resolve a hostname to one IPv4.

$ python -c 'import socket,sys; print(socket.gethostbyname(sys.argv[1]))' example.com

Encode a file to base64 on stdout.

$ python -c 'import base64,pathlib,sys; sys.stdout.buffer.write(base64.b64encode(pathlib.Path(sys.argv[1]).read_bytes()))' payload.bin

Decode a base64 string.

$ echo 'b3BlcmF0b3I=' | python -c 'import base64,sys; sys.stdout.buffer.write(base64.b64decode(sys.stdin.read()))'

URL-encode an argument.

$ python -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' 'space & ampersand'

Quick HTTP server on the current directory (operator’s file-share scratchpad).

$ python -m http.server 8000

Pretty-print a TOML file (Python 3.11+).

$ python -c 'import tomllib,sys,json; print(json.dumps(tomllib.load(sys.stdin.buffer), indent=2))' < config.toml

Current UTC time in ISO-8601.

$ python -c 'from datetime import datetime, timezone; print(datetime.now(timezone.utc).isoformat())'

Epoch seconds.

$ python -c 'import time; print(int(time.time()))'

Generate a 32-byte hex token suitable for an API key.

$ python -c 'import secrets; print(secrets.token_hex(32))'

UUID v4.

$ python -c 'import uuid; print(uuid.uuid4())'

References#

  • Snippets for the rest of the snippets catalogue.

  • CLI scripting for argparse / sys.argv when one-liners outgrow python -c.

  • dict for dict.fromkeys and merge operators.

  • Algorithms for the algorithms behind these idioms.