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
| Option | What it does |
|---|---|
-c 'code' | run code from a string |
-m module | run a module (http.server, json.tool, venv…) |
-u | unbuffered stdout/stderr — output shows up immediately in a log and in a pipeline |
-q | don't print the banner in interactive mode |
-i | stay in the interactive console after running |
-B | don't create __pycache__ |
-I | isolated mode: no PYTHON* variables and no user packages |
-V | version |
Useful modules for -m
| Command | What it does |
|---|---|
python3 -m http.server [port] | serve the current directory over HTTP (port 8000 by default) |
… -b address / -d dir | listen only on this address / serve another directory |
python3 -m json.tool [in [out]] | validate and format JSON |
… --sort-keys, --indent N, --tab, --compact | sort keys, indent, tabs, one line without spaces |
… --no-ensure-ascii | write non-ASCII characters such as é as is, not as \u00e9… |
… --json-lines | input is JSON Lines (one object per line) |
python3 -m venv dir | create a virtual environment |
python3 -m pip … | package manager (if installed) |
python3 -m base64 [-d] | base64 encode / decode |
python3 -m gzip [-d] file | compress / decompress |
python3 -m zipfile -l|-e|-c | list / extract / create a zip |
python3 -m tarfile -l|-e|-c | the same for tar |
python3 -m sqlite3 file.db 'SQL' | SQLite console without the sqlite3 package |
python3 -m uuid | random UUID |
python3 -m calendar 2026 10 | calendar |
python3 -m timeit 'expression' | time an expression |
python3 -m py_compile file.py | check 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
pythoncommand. Ubuntu only haspython3;pythonappears only with thepython-is-python3package. python3 -m venvon Ubuntu fails without thepython3-venvpackage (ensurepip is not available), leaving a half-made directory. Without the package,python3 -m venv --without-pip dirworks — the environment will have nopip. In the IzzyLab sandboxpython3-venvandpipare not installed.http.serverlistens 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 supportRange(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.toolescapes non-ASCII characters as\uXXXX. Need readable text —--no-ensure-ascii; in your own code —json.dumps(…, ensure_ascii=False).- In
-cyou can't put a compound statement after;.for …: if …: …on one line is aSyntaxError. Use comprehensions ([… for … if …]), a newline inside the quotes or a heredocpython3 - <<'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 needint()orfloat().