Skip to content

Commit

Permalink
Python 3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
em1181 committed Nov 25, 2014
1 parent 0a376d1 commit 2297595
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__
*.pyc

32 changes: 27 additions & 5 deletions pawk.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""cat input | pawk [<options>] <expr>
Expand All @@ -9,16 +10,37 @@
"""

import ast
import codecs
import inspect
import os
import optparse
import os
import re
import sys


RESULT_VAR_NAME = "__result"


if sys.version_info[0] > 2:
try:
exec_ = __builtins__['exec']
except TypeError:
exec_ = getattr(__builtins__, 'exec')
STRING_ESCAPE = 'unicode_escape'
else:
def exec_(_code_, _globs_=None, _locs_=None):
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
STRING_ESCAPE = 'string_escape'


# Store the last expression, if present, into variable var_name.
def save_last_expression(tree, var_name=RESULT_VAR_NAME):
body = tree.body
Expand All @@ -37,8 +59,8 @@ def compile_command(text):


def eval_in_context(codeobj, context, var_name=RESULT_VAR_NAME):
exec codeobj in globals(), context
return context.pop(var_name)
exec_(codeobj, globals(), context)
return context.pop(var_name)


class Action(object):
Expand Down Expand Up @@ -116,8 +138,8 @@ def from_options(cls, options, modules):
m = __import__(imp.strip(), fromlist=['.'])
self.update((k, v) for k, v in inspect.getmembers(m) if k[0] != '_')

self.delim = options.delim.decode('string_escape') if options.delim else None
self.odelim = options.delim_out.decode('string_escape')
self.delim = codecs.decode(options.delim, STRING_ESCAPE) if options.delim else None
self.odelim = codecs.decode(options.delim_out, STRING_ESCAPE)

for m in modules:
try:
Expand Down
10 changes: 8 additions & 2 deletions pawk_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# -*- coding: utf-8 -*-
import sys
import timeit
from pawk import Action, Context, run, parse_commandline
from StringIO import StringIO

if sys.version_info[0] > 2:
from io import StringIO
else:
from StringIO import StringIO


TEST_INPUT_LS = r'''
Expand Down Expand Up @@ -74,7 +80,7 @@ def benchmark_fields():
action = Action(cmd='f')
context = Context.from_options(options, [])
t = timeit.Timer(lambda: action.apply(context, 'foo bar waz was haz has hair'))
print t.repeat(repeat=3, number=100000)
print((t.repeat(repeat=3, number=100000)))


if __name__ == '__main__':
Expand Down

0 comments on commit 2297595

Please sign in to comment.