-
Notifications
You must be signed in to change notification settings - Fork 30
/
run_sed
executable file
·56 lines (44 loc) · 1.62 KB
/
run_sed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python2
"""Run sed from a script, but do it as though it is being used in a Makefile.
The difference between this and its use in the makefile itself is that here we
don't escape $ to $$.
"""
from __future__ import print_function, division
import os
import sys
from optparse import OptionParser
from util import template
def main(opts, args):
ns = template.Template()
cmd_args = ["sed"]
text = ns.expand_file(args[0],
variables=opts.sed_args,
transform_after=ns.xfunc_sed_lines_to_args())
cmd_args.extend(text.split('\n'))
cmd_args.extend(args[1:])
if opts.show_cmd:
import pprint
pprint.pprint(cmd_args, stream=sys.stderr)
print("sed args:")
pprint.pprint(opts.sed_args)
# Ensure that sed still works with international characters (and doesn't just
# hang)
os.putenv("LANG", "C")
with os.popen(" ".join(cmd_args)) as f:
print(f.read())
def on_sed_arg(option, opt_str, value, parser, *args, **kwargs):
pieces = value.split('=', 1)
if len(pieces) != 2:
raise ValueError(
"invalid sed argument: expected 'name=val', got {0!r}".format(value))
parser.values.ensure_value("sed_args", {})[pieces[0]] = pieces[1]
if __name__ == '__main__':
op = OptionParser()
op.add_option("-c", "--show_cmd", dest="show_cmd", default=False,
action="store_true", help="show sed script")
op.add_option("-a", "--arg", action="callback", callback=on_sed_arg,
type="string",
help="add an argument to the sed script")
opts, args = op.parse_args()
opts.ensure_value("sed_args", {})
main(opts, args)