-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyargs
More file actions
executable file
·113 lines (97 loc) · 3.36 KB
/
Copy pathpyargs
File metadata and controls
executable file
·113 lines (97 loc) · 3.36 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/python -u
import argparse
import functools
import inspect
import itertools
import os
import re
import subprocess
import sys
## tools
class kdict(dict):
def __missing__(self, key):
return getattr(self['__builtins__'], key, key)
class FuncAction(argparse.Action):
def __init__(self, *args, **kwargs):
self.func = kwargs.pop('func', None)
kwargs.setdefault('nargs', '*')
kwargs['dest'] = 'actions'
kwargs.setdefault('default', [])
super(FuncAction, self).__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest, None)
items.append(functools.partial(self.func, namespace, values))
## functions
def _execute(args, expr_parts, context, it):
expr = 'x = (%s)' % ' '.join(expr_parts)
for i, x in enumerate(it):
context.update(i=i, x=x)
exec expr in context
if context['x']:
yield context['x']
def _execute_imploded(args, expr_parts, context, it):
expr = 'x = (%s)' % ' '.join(expr_parts)
context.update(x=list(it))
exec expr in context
x = context['x']
if x:
if isinstance(x, basestring):
yield x
try:
for y in x:
yield y
except TypeError:
yield x
def _filter(args, expr_parts, context, it):
expr_parts = ('(%s) and x ' % ' '.join(expr_parts)).split(' ')
return _execute(args, expr_parts, context, it)
def _print(args, expr_parts, context, it):
for x in it:
print x
yield x
def _sh(args, expr_parts, context, it):
expr_pattern = ' '.join(expr_parts)
for i, x in enumerate(it):
expr = expr_pattern.replace('XX', x).replace('II', str(i))
yield subprocess.check_output(expr, shell=True).rstrip()
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--exec', '-x', action=FuncAction, func=_execute)
parser.add_argument('--iexec', '-X', action=FuncAction, func=_execute_imploded)
parser.add_argument('--filter', '-f', action=FuncAction, func=_filter)
parser.add_argument('--sh', '-s', action=FuncAction, func=_sh)
parser.add_argument('--print', '-p', action=FuncAction, func=_print, nargs=0)
parser.add_argument('--implode', '-I', action='store_true')
parser.add_argument('--delimiter', '-d')
parser.add_argument('last_action', nargs='*')
return parser.parse_args()
def run(args):
it = iter(sys.stdin.readline, '')
if args.delimiter:
def f(it0):
delim = args.delimiter
left = ''
for line in it0:
splitteds = (left + line).split(delim)
for x in splitteds[:-1]:
yield x
left = splitteds[-1]
yield left
it = f(it)
else:
it = itertools.imap(lambda x: x.rstrip(), it)
it_func = list if args.implode else lambda x: x
if args.last_action:
args.actions.append(functools.partial(_execute, args, args.last_action))
for action in args.actions:
context = kdict([kv for kv in globals().items() if inspect.ismodule(kv[1])])
it = it_func(action(context, it))
for x in it:
if x:
print x
if __name__ == '__main__':
args = parse()
try:
run(args)
except KeyboardInterrupt as err:
pass