Advertisement
MeaCulpa

py awk wrapper

Jul 4th, 2012
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from subprocess import Popen, PIPE
  2. from tempfile import NamedTemporaryFile
  3. import os
  4.  
  5. def pyawk(input_data, script, params=None):
  6.     """
  7.    A simple AWK Wrapper; Bye-Bye regex!!!
  8.  
  9.    For example::
  10.  
  11.        input = '''
  12.            1 2 3 4
  13.            5 6 7 8
  14.        '''
  15.        script = '''
  16.            { print;
  17.              print $A;
  18.              print "Don't forget to escape \\n \\\\n!"
  19.              print $B;
  20.            }
  21.        '''
  22.        params= {'A':'1',
  23.                'B':'0'}
  24.  
  25.        print pyawk(input, script, params)
  26.    """
  27.     # Load script to tmp file
  28.     script = dedent(script).strip()
  29.     #script = shell_escape(script)
  30.     tmpf = NamedTemporaryFile(delete=False)
  31.     tmpf.write(script)
  32.     tmpf.flush()
  33.     tmpf.close()
  34.  
  35.     # Build commandline
  36.     #pcmd = ['/usr/bin/gawk']
  37.     pcmd = ['/usr/bin/mawk']
  38.     pcmd.append('-f' + tmpf.name)
  39.     if params:
  40.         pcmd += list('-v' + k + '=' + v for k, v in params.iteritems() )
  41.     #script = dedent(script).strip()
  42.     if __DEBUG__: print "commandline:", pcmd
  43.  
  44.     # Run command
  45.     p = Popen(pcmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
  46.     output = p.communicate(input=input_data)
  47.  
  48.     try:
  49.         os.remove(tmpf.name)
  50.     except OSError:
  51.         pass
  52.  
  53.     # Return stdout or stderr
  54.     if p.returncode == 0:
  55.         return output[0]
  56.     else:
  57.         return output[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement