← Full reference

python3 one-liners

python3 -c and -m — web server, JSON validation, venv, parsing CSV and JSON right on the command line

python3 is on almost every Linux server, so it makes a handy "Swiss army knife" right from the shell: do some math, parse CSV with quotes, reformat JSON, spin up a web server for a minute. You don't need to write a file for this — -c 'code' or -m module is enough.

Syntax

python3 [options] -c 'code' [args…]       # run a string
python3 [options] -m module [args…]       # run a module as a program
python3 [options] file.py [args…]         # run a file
python3 - [args…] <<'EOF'                 # program from stdin
…
EOF

Arguments after the code end up in sys.argv[1:].

Interpreter options

OptionWhat it does
-c 'code'run code from a string
-m modulerun a module (http.server, json.tool, venv…)
-uunbuffered stdout/stderr — output shows up immediately in a log and in a pipeline
-qdon't print the banner in interactive mode
-istay in the interactive console after running
-Bdon't create __pycache__
-Iisolated mode: no PYTHON* variables and no user packages
-Vversion

Useful modules for -m

CommandWhat it does
python3 -m http.server [port]serve the current directory over HTTP (port 8000 by default)
… -b address / -d dirlisten only on this address / serve another directory
python3 -m json.tool [in [out]]validate and format JSON
… --sort-keys, --indent N, --tab, --compactsort keys, indent, tabs, one line without spaces
… --no-ensure-asciiwrite non-ASCII characters such as é as is, not as \u00e9…
… --json-linesinput is JSON Lines (one object per line)
python3 -m venv dircreate a virtual environment
python3 -m pip …package manager (if installed)
python3 -m base64 [-d]base64 encode / decode
python3 -m gzip [-d] filecompress / decompress
python3 -m zipfile -l|-e|-clist / extract / create a zip
python3 -m tarfile -l|-e|-cthe same for tar
python3 -m sqlite3 file.db 'SQL'SQLite console without the sqlite3 package
python3 -m uuidrandom UUID
python3 -m calendar 2026 10calendar
python3 -m timeit 'expression'time an expression
python3 -m py_compile file.pycheck a file's syntax

Exit codes

0 — success; 1 — an unhandled exception (Traceback) or a syntax error; anything else — via sys.exit(N). sys.exit('text') prints the text to stderr and returns 1.

Examples

# calculator
python3 -c 'print(2**64, 7/3, round(7/3, 2))'

# arguments from the command line
python3 -c 'import sys; print(sys.argv[1].upper())' hello

# serve a directory on localhost:8000, local only
python3 -m http.server 8000 -b 127.0.0.1 -d /srv/www

# validate and pretty-print JSON; on an error — code 1 and the error location
echo '{"b":1,"a":[1,2]}' | python3 -m json.tool --sort-keys
python3 -m json.tool --no-ensure-ascii data.json

# CSV with quotes and commas inside fields — cut breaks here
printf 'name,age,city\nAnn,30,"New York, NY"\nBob,25,Paris\n' > people.csv
python3 -c 'import csv,sys; [print(r["city"]) for r in csv.DictReader(sys.stdin)]' < people.csv

# sum of a column
python3 -c 'import csv,sys; print(sum(int(r["age"]) for r in csv.DictReader(open(sys.argv[1]))))' people.csv

# CSV → JSON
python3 -c 'import csv,json,sys; print(json.dumps(list(csv.DictReader(sys.stdin)), ensure_ascii=False))' < people.csv

# extract a field from JSON
echo '{"items":[{"n":"a"},{"n":"b"}]}' | python3 -c 'import json,sys; print(*[i["n"] for i in json.load(sys.stdin)["items"]], sep="\n")'

# YAML → JSON (if PyYAML is installed)
python3 -c 'import yaml,json,sys; print(json.dumps(yaml.safe_load(sys.stdin)))' < config.yaml

# HTTP request without curl
python3 -c 'import urllib.request as u; print(u.urlopen("http://127.0.0.1:8000/").status)'

# random token, URL encoding, date from Unix time
python3 -c 'import secrets; print(secrets.token_hex(16))'
python3 -c 'import urllib.parse as p; print(p.quote("a b/c"))'
python3 -c 'import datetime as d; print(d.datetime.fromtimestamp(1700000000, d.UTC))'

# multi-line program without a file
python3 - <<'EOF'
import json
with open("data.json") as f:
    data = json.load(f)
print(len(data))
EOF

Pitfalls

  • There may be no python command. Ubuntu only has python3; python appears only with the python-is-python3 package.
  • python3 -m venv on Ubuntu fails without the python3-venv package (ensurepip is not available), leaving a half-made directory. Without the package, python3 -m venv --without-pip dir works — the environment will have no pip. In the IzzyLab sandbox python3-venv and pip are not installed.
  • http.server listens on all interfaces by default (0.0.0.0) and serves the directory to anyone who can reach it. For a local check add -b 127.0.0.1. It's a debugging server, not for production: it doesn't support Range (resumed downloads) or HTTPS.
  • Output buffering. To a file or a pipeline Python writes in blocks, and lines show up with a delay — or not at all if the process is killed. For example, the Serving HTTP on … banner won't make it into the log with > log. Add -u.
  • json.tool escapes non-ASCII characters as \uXXXX. Need readable text — --no-ensure-ascii; in your own code — json.dumps(…, ensure_ascii=False).
  • In -c you can't put a compound statement after ;. for …: if …: … on one line is a SyntaxError. Use comprehensions ([… for … if …]), a newline inside the quotes or a heredoc python3 - <<'EOF'.
  • Quotes. Put the code in single shell quotes and the Python strings inside in double quotes. Then bash won't touch $ and !.
  • CSV values are always strings. r["age"] is "30"; for arithmetic you need int() or float().

See also

jq · yq · curl · base64 · sqlite3 · cut