Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from subprocess import Popen, PIPE
- from tempfile import NamedTemporaryFile
- import os
- def pyawk(input_data, script, params=None):
- """
- A simple AWK Wrapper; Bye-Bye regex!!!
- For example::
- input = '''
- 1 2 3 4
- 5 6 7 8
- '''
- script = '''
- { print;
- print $A;
- print "Don't forget to escape \\n \\\\n!"
- print $B;
- }
- '''
- params= {'A':'1',
- 'B':'0'}
- print pyawk(input, script, params)
- """
- # Load script to tmp file
- script = dedent(script).strip()
- #script = shell_escape(script)
- tmpf = NamedTemporaryFile(delete=False)
- tmpf.write(script)
- tmpf.flush()
- tmpf.close()
- # Build commandline
- #pcmd = ['/usr/bin/gawk']
- pcmd = ['/usr/bin/mawk']
- pcmd.append('-f' + tmpf.name)
- if params:
- pcmd += list('-v' + k + '=' + v for k, v in params.iteritems() )
- #script = dedent(script).strip()
- if __DEBUG__: print "commandline:", pcmd
- # Run command
- p = Popen(pcmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
- output = p.communicate(input=input_data)
- try:
- os.remove(tmpf.name)
- except OSError:
- pass
- # Return stdout or stderr
- if p.returncode == 0:
- return output[0]
- else:
- return output[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement