Skip to content

Instantly share code, notes, and snippets.

@tbc
Forked from dgulino/pyliner.py
Last active October 19, 2026 15:03
Show Gist options
  • Select an option

  • Save tbc/68dfb5cd8518eee690931848a3a78699 to your computer and use it in GitHub Desktop.

Select an option

Save tbc/68dfb5cd8518eee690931848a3a78699 to your computer and use it in GitHub Desktop.
Python script that runs one-liner python scripts similarly to how Perl runs themportions based on http://code.activestate.com/recipes/437932-pyline-a-grep-like-sed-like-command-line-tool/(Graham Fawcett, Jacob Oscarson, Mark Eichin)interface inspired by Perl
#!/usr/bin/env python3
#-*-Python-*-
"""pyliner: run one-liner Python scripts over input, similar to Perl's -lane.
Modified October 2026 by Tim Chambers (with Claude Sonnet 5.5).
Consolidated from Drew’s gist (https://gist.github.com/dgulino/4750088) and
Sparky’s 2014 fork (literal colon and semicolon, -h, re import).
**Summary**
Drew's gist and Sparky's 2014 fork both fail their own documented example (`BEGIN:sum=0#/if I(0) > 90:sum+=I(0) END:print(sum)#/`) on Python 3.13, with `TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'`. The cause is `eval(code, globals(), locals())`. On 3.13, `locals()` inside a function returns a fresh snapshot on every call, so variables set in BEGIN, and modules bound by `-M`, are lost before the main loop runs. (Claude did not test older Pythons; it believes earlier versions reused one dict, which hid the problem.)
**What changed**
- One persistent namespace now shared by BEGIN, the input loop and END.
- `-M` and `-h` kept from the 2014 fork; dotted names work (`-M os.path` binds `os`). `re`, `sys`, `os` are preloaded.
- Literal `::` and `;;` kept from the 2014 fork, reimplemented as a one-pass scanner instead of placeholder substitution.
- BEGIN/END parsed with regexes; a trailing `END:` no longer needs `#/`.
- If a section is a single expression, its value is printed (the old result-printing code never ran, since `eval` of exec-mode code returns None).
- Syntax and runtime errors go to stderr with the input line number and a nonzero exit code; `| head` exits quietly.
- `-l` strips only the line ending; `-V` added; `-o` writes to stderr; no script prints usage; Python 3 only.
**Not changed**
- `-p` still prints the line before running the script (Perl prints after).
- Input is stdin only; `:` always opens a block, so slices, dicts and lambdas need `::`.
**Tested** on Python 3.13 only: the sum example (1100), the average example, if/else with `?;`, literal `::` and `;;`, `-M random` with `random.shuffle`, `-o`, `-h`, `-V`, bad syntax, a runtime error, and piping to `head`. Not tested: Python 2, older Python 3 releases, Windows.
**Notes for Drew** (in his gist's header examples): `a=F(0)` should be `f(0)`, since `F` is the split list; `END:print(sum)/NR` should be `print(sum/NR)`.
Consolidated and tested with Claude Sonnet 5.5. Chat: https://claude.ai/share/c47f3d2a-7873-410b-adc0-794abd7dec3d
Portions based on
http://code.activestate.com/recipes/437932-pyline-a-grep-like-sed-like-command-line-tool/
(Graham Fawcett, Jacob Oscarson, Mark Eichin). Interface inspired by Perl.
Copyright (C) 2010, 2025 Drew Gulino
Copyright (C) 2014, 2026 Tim ‘Sparky’ Chambers aka tbc
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import getopt
import importlib
import os
import re
import sys
__version__ = "3.0"
USAGE = """\
Usage: {prog} [options] "script"
-a auto-split each input line into the list F
-F separator for -a (default: any whitespace)
-p loop over input, printing each line before running the script
-n loop over input without printing it
-l strip the trailing newline from each input line
-M import modules, comma separated (e.g. -M json,os.path)
-h print help() for the given modules, comma separated, and exit
-o show the parsed, indented script on stderr
-e accepted and ignored (Perl compatibility)
-V print version and exit
preloaded modules: sys, re, os
variables:
line current input line
F split input (with -a)
NR current input line number
functions:
I(x) F[x] as an integer
f(x) F[x] as a float
script syntax:
; newline
: end of a block opener; following lines are indented
:: a literal colon
;; a literal semicolon
?; newline, then dedent one level
/; newline, then dedent to the far left
BEGIN: ... #/ code run once before the input loop
END: ... #/ code run once after the input loop (the #/ is
optional if END: is last)
If a section is a single expression, its value is printed (lists and
tuples are joined with spaces; None and False print nothing).
Variables persist across BEGIN, the loop and END.
"""
INDENT = " "
def split_script(text):
"""Turn pyliner syntax into Python source.
Scans once, left to right, so literal '::' and ';;' never collide with
the block markers (the older versions used placeholder substitution).
"""
lines = []
cur = []
indent = 0
def flush(after):
nonlocal indent
body = "".join(cur).strip()
cur.clear()
if body:
lines.append(INDENT * indent + body)
if after == "open":
indent += 1
elif after == "dedent":
indent = max(indent - 1, 0)
elif after == "reset":
indent = 0
i, n = 0, len(text)
while i < n:
two = text[i:i + 2]
if two == "?;":
flush("dedent")
i += 2
elif two == "/;":
flush("reset")
i += 2
elif two == ";;":
cur.append(";")
i += 2
elif two == "::":
cur.append(":")
i += 2
elif text[i] == ";":
flush(None)
i += 1
elif text[i] == ":":
cur.append(":")
flush("open")
i += 1
else:
cur.append(text[i])
i += 1
flush(None)
return "\n".join(lines)
def extract_sections(cmd):
"""Return (begin, body, end) source strings from the raw script."""
begin = end = ""
m = re.search(r"\bBEGIN:(.*?)#/", cmd, re.S)
if m:
begin = m.group(1)
cmd = cmd[:m.start()] + cmd[m.end():]
m = re.search(r"\bEND:(.*?)(?:#/|$)", cmd, re.S)
if m:
end = m.group(1)
cmd = cmd[:m.start()] + cmd[m.end():]
return begin, cmd, end
def build(label, raw, show):
"""Compile one section. Single expressions are evaluated and printed."""
if not raw.strip():
return None
source = split_script(raw)
if show:
sys.stderr.write("%s\n%s\n\n" % (label, source))
try:
return compile(source, label, "eval")
except SyntaxError:
pass
try:
return compile(source, label, "exec")
except SyntaxError as err:
sys.exit("pyliner: syntax error in %s: %s\n%s" % (label, err, source))
def emit(result):
if result is None or result is False:
return
if isinstance(result, (list, tuple)):
result = " ".join(map(str, result))
sys.stdout.write(str(result) + "\n")
def run(code, ns):
if code is not None:
emit(eval(code, ns))
def import_module(name):
name = name.strip()
importlib.import_module(name)
top = name.split(".")[0]
return top, sys.modules[top]
def main(argv):
prog = os.path.basename(argv[0])
try:
opts, args = getopt.getopt(argv[1:], "oaplneVh:M:F:")
except getopt.GetoptError as err:
sys.stderr.write("pyliner: %s\n" % err)
sys.stderr.write(USAGE.format(prog=prog))
return 2
opts = dict(opts)
if "-V" in opts:
print("version: " + __version__)
return 0
if "-h" in opts:
for name in opts["-h"].split(","):
try:
help(importlib.import_module(name.strip()))
except ImportError as err:
sys.stderr.write("pyliner: %s\n" % err)
return 1
return 0
cmd = " ".join(args)
if not cmd.strip():
sys.stdout.write(USAGE.format(prog=prog))
return 0
ns = {"__name__": "__pyliner__", "sys": sys, "re": re, "os": os,
"F": [], "line": "", "NR": 0}
ns["I"] = lambda x: int(ns["F"][x])
ns["f"] = lambda x: float(ns["F"][x])
for name in opts.get("-M", "").split(","):
if name.strip():
try:
top, mod = import_module(name)
except ImportError as err:
sys.stderr.write("pyliner: %s\n" % err)
return 1
ns[top] = mod
show = "-o" in opts
begin_raw, body_raw, end_raw = extract_sections(cmd)
begin = build("BEGIN", begin_raw, show)
body = build("script", body_raw, show)
end = build("END", end_raw, show)
sep = opts.get("-F") # None means split on any whitespace
loop = "-p" in opts or "-n" in opts
run(begin, ns)
if loop:
for num, text in enumerate(sys.stdin, 1):
if "-l" in opts:
text = text.rstrip("\r\n")
ns["line"], ns["NR"] = text, num
if "-p" in opts:
print(text, end="" if text.endswith("\n") else "\n")
if "-a" in opts:
ns["F"] = [w for w in text.split(sep) if w]
try:
run(body, ns)
except BrokenPipeError:
raise
except Exception as err:
sys.stderr.write("pyliner: line %d: %s: %s\n"
% (num, type(err).__name__, err))
return 1
else:
run(body, ns)
run(end, ns)
return 0
if __name__ == "__main__":
try:
sys.exit(main(sys.argv))
except BrokenPipeError:
# e.g. `... | head`: silence the second error raised at interpreter exit
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment