forked from ywangd/stash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxargs.py
59 lines (44 loc) · 1.5 KB
/
xargs.py
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
57
58
59
""" Construct argument list(s) and execute utility
"""
import os
import sys
import argparse
_stash = globals()['_stash']
def main(args):
ap = argparse.ArgumentParser()
ap.add_argument('-n',
nargs='?',
metavar='number',
type=int,
help='maximum number of arguments taken from standard input for each invocation of utility')
ap.add_argument('-I',
dest='replstr',
nargs='?',
help='replacement string')
ap.add_argument('utility',
nargs='?',
default='echo',
help='utility to invoke')
ap.add_argument('args_to_pass',
metavar='arguments',
nargs=argparse.REMAINDER,
help='arguments to the utility')
ns = ap.parse_args(args)
lines = [line.strip() for line in sys.stdin.readlines()]
n = ns.n if ns.n else len(lines)
if ns.replstr:
n = 1
while lines:
rest = ' '.join(lines[:n])
lines = lines[n:]
args_to_pass = ' '.join(ns.args_to_pass)
if rest.strip():
if ns.replstr:
args_to_pass = args_to_pass.replace(ns.replstr, rest)
rest = ''
cmdline = '%s %s %s' % (ns.utility,
args_to_pass,
rest)
_stash(cmdline)
if __name__ == "__main__":
main(sys.argv[1:])