-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpyeval.py
More file actions
executable file
·372 lines (289 loc) · 12.1 KB
/
Copy pathpyeval.py
File metadata and controls
executable file
·372 lines (289 loc) · 12.1 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
from __future__ import (unicode_literals, absolute_import,
print_function, division)
from functools import lru_cache
from itertools import count, islice
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
import argparse
import collections
import collections.abc
import contextlib
import importlib
import inspect
import json
import pydoc
import sys, re, io
import os, site
if 'VIRTUAL_ENV' in os.environ:
# derived from activate_this.py from the virtualenv package
base = os.environ['VIRTUAL_ENV']
os.environ['PATH'] = os.pathsep.join([os.path.join(base, 'bin')] + os.environ['PATH'].split(os.pathsep))
prev_length = len(sys.path)
site.addsitedir(os.path.realpath(site._get_path(base)))
sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
sys.prefix = base
sys.path.insert(0, '')
cache = lambda function: lru_cache(maxsize=128, typed=True)(function)
try:
from pythonpy.__version__ import __version__
except (ImportError, ValueError, SystemError):
__version__ = '0.5.5'
pyversion = sys.version.split(' ')[0]
version_string = f'''Pythonpy {__version__}
Python {pyversion}'''
module_aliases = {
'mp' : 'matplotlib',
'np' : 'numpy',
'pd' : 'pandas',
'tf' : 'tensorflow',
'xa' : 'xarray'
}
ModuleAlias = collections.namedtuple('ModuleAlias', ('shorthand', 'modname'))
IOHandles = collections.namedtuple('IOHandles', ('out', 'err'))
aliases = { re.compile(rf"^{key}") : ModuleAlias(shorthand=key, modname=value) \
for key, value \
in module_aliases.items() }
def iterlen(iterable):
""" iterlen(iterable) → Return the number of items in “iterable.”
This will consume iterables without a “__len__()” method – be careful!
"""
# Stolen from “more-itertools”: http://bit.ly/2LUZqCx
try:
return len(iterable)
except TypeError as exc:
if 'has no len' in str(exc):
counter = count()
collections.deque(zip(iterable, counter), maxlen=0)
return next(counter)
raise
@cache
def import_matches(query, prefix=''):
for raw_module_name in frozenset(
re.findall(
rf"({prefix}[a-zA-Z_][a-zA-Z0-9_]*)\.?", query)):
module_name = raw_module_name
# Only de-alias module names at the top level,
# and at most de-alias once:
if prefix == '':
for rgx, alias in aliases.items():
if rgx.match(module_name):
module_name = rgx.sub(alias.modname, module_name)
break
try:
module = importlib.import_module(module_name)
except (ModuleNotFoundError, ImportError):
pass
else:
globals()[raw_module_name] = module
if module_name != raw_module_name:
globals()[module_name] = module
yield module
yield from import_matches(query, prefix=rf"{module_name}\.")
def lazy_imports(*args):
query = ' '.join(x for x in args if x)
yield from import_matches(query)
def current_list(input):
return current_list.rgx.split(input)
current_list.rgx = re.compile(r'[^a-zA-Z0-9_\.]')
def inspect_source(instance):
try:
return ''.join(inspect.getsourcelines(instance)[0])
except:
return help(instance)
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
add_help=False)
group = parser.add_argument_group("Options")
parser.add_argument('expression', nargs='?', default='None',
help="e.g. “py '2 ** 32'”")
group.add_argument('-x', dest='lines_of_stdin',
action='store_const',
const=True, default=False,
help='treat each row of stdin as “x”')
group.add_argument('-fx', dest='filter_result',
action='store_const',
const=True, default=False,
help=argparse.SUPPRESS)
group.add_argument('-l', dest='list_of_stdin',
action='store_const',
const=True, default=False,
help='treat list of stdin as “l”')
group.add_argument('--ji', '--json_input',
dest='json_input',
action='store_const',
const=True, default=False,
help=argparse.SUPPRESS)
group.add_argument('--jo', '--json_output',
dest='json_output',
action='store_const',
const=True, default=False,
help=argparse.SUPPRESS)
group.add_argument('--si', '--split_input',
dest='input_delimiter',
help=argparse.SUPPRESS)
group.add_argument('--so', '--split_output',
dest='output_delimiter',
help=argparse.SUPPRESS)
group.add_argument('-p', '--pager',
dest='pager',
action='store_const',
const=True, default=False,
help=argparse.SUPPRESS)
group.add_argument('-c', dest='pre_cmd', help='run code before expression')
group.add_argument('-C', dest='post_cmd', help='run code after expression')
group.add_argument('--i', '--ignore_exceptions',
dest='ignore_exceptions',
action='store_const',
const=True, default=False,
help=argparse.SUPPRESS)
group.add_argument('-v', '--verbose',
dest='verbosity',
action='count', default=0,
help='set the verbosity level (default=0)')
group.add_argument('-V', '--version', action='version',
version=version_string,
help='show the current version and exit')
group.add_argument('-h', '--help', action='help',
help="show this help message and exit")
def exit(*args, **kwargs):
""" Craft and return (without raising!) a SystemExit exception """
exc = SystemExit("\n\t".join(args))
return exc
@contextlib.contextmanager
def redirect(args):
""" Redirect “stdout” and “stderr” at the same time """
out, err = io.StringIO(), io.StringIO()
with contextlib.ExitStack() as ctx:
ctx.enter_context(contextlib.redirect_stdout(out))
ctx.enter_context(contextlib.redirect_stderr(err))
iohandles = IOHandles(out=out, err=err)
try:
yield iohandles
except SystemExit as exc:
raise exit("[ERROR] in cluval execution:", str(exc))
except BaseException as exc:
import traceback
pyheader = 'pythonpy/pyeval.py'
exprheader = 'File "<string>"'
foundexpr = False
lines = traceback.format_exception(*sys.exc_info())
for line in lines:
if pyheader in line:
continue
iohandles.err.write(line)
if not foundexpr and line.lstrip().startswith(exprheader) and not isinstance(exc, SyntaxError):
iohandles.err.write(' {}\n'.format(args.expression))
foundexpr = True
raise exit(iohandles.err.getvalue())
def safe_eval(code, x):
try:
return eval(code)
except:
return None
def pyeval(argv=None):
""" Evaluate a Python expression from a set of CLI arguments. """
args = parser.parse_args(argv or sys.argv[1:])
with redirect(args) as iohandles:
if sum([args.list_of_stdin, args.lines_of_stdin, args.filter_result]) > 1:
raise exit('Pythonpy accepts at most one of [-x, -l] flags\n')
if args.json_input:
def loads(string):
try:
return json.loads(string.rstrip())
except BaseException as exc:
if args.ignore_exceptions:
pass
else:
raise exc
stdin = (loads(x) for x in sys.stdin)
elif args.input_delimiter:
stdin = (re.split(args.input_delimiter, x.rstrip()) for x in sys.stdin)
else:
stdin = (x.rstrip() for x in sys.stdin)
if args.expression:
args.expression = args.expression.replace("`", "'")
if args.expression.endswith('…'):
args.expression = args.expression[:-1]
args.pager = True
if args.expression.startswith('?') or args.expression.endswith('?'):
final_atom = current_list(args.expression.rstrip('?'))[-1]
first_atom = current_list(args.expression.lstrip('?'))[0]
if args.expression.startswith('??'):
args.expression = f"inspect_source({first_atom})"
elif args.expression.endswith('??'):
args.expression = f"inspect_source({final_atom})"
elif args.expression.startswith('?'):
args.expression = f'inspect.getdoc({first_atom})'
else:
args.expression = f'inspect.getdoc({final_atom})'
args.pager = True
if args.lines_of_stdin:
stdin = islice(stdin, 1)
if args.expression.startswith('help('):
args.pager = True
if args.pre_cmd:
args.pre_cmd = args.pre_cmd.replace("`", "'")
if args.post_cmd:
args.post_cmd = args.post_cmd.replace("`", "'")
# DO THE IMPORTS:
modules = tuple(lazy_imports(args.expression,
args.pre_cmd,
args.post_cmd))
# Print a list of any imported modules
if args.verbosity and len(modules):
from pprint import pprint
print("Imported modules:")
pprint(modules)
print()
if args.pre_cmd:
exec(args.pre_cmd)
if args.lines_of_stdin:
if args.ignore_exceptions:
result = (safe_eval(args.expression, x) for x in stdin)
else:
result = (eval(args.expression) for x in stdin)
elif args.filter_result:
if args.ignore_exceptions:
result = (x for x in stdin if safe_eval(args.expression, x))
else:
result = (x for x in stdin if eval(args.expression))
elif args.list_of_stdin:
locals()['l'] = list(stdin)
result = eval(args.expression)
else:
result = eval(args.expression)
def prepare(output):
if output is None:
return None
elif args.json_output:
return json.dumps(output)
elif args.output_delimiter:
return args.output_delimiter.join(output)
else:
return output
if isinstance(result, collections.abc.Iterable) and not \
isinstance(result, (str, bytes)):
for x in result:
formatted = prepare(x)
if formatted is not None:
iohandles.out.write(f"{formatted}\n")
else:
formatted = prepare(result)
if formatted is not None:
iohandles.out.write(f"{formatted}\n")
if args.post_cmd:
exec(args.post_cmd)
sys.stdout.flush()
# Extract rerouted «stdout» value:
out = iohandles.out.getvalue()
# Return extracted «stdout» and whether or not to page:
return out, args.pager
def main():
out, pager = pyeval()
if pager:
pydoc.pager(out)
else:
print(out, end='')
if __name__ == '__main__':
main()