Create a gist now

Instantly share code, notes, and snippets.

@rosarinjroy /py
Last active Dec 19, 2015

What would you like to do?
This is a simple script which will execute the given argument like "perl -ne".
#!/usr/bin/env python
#
# Author: Rosarin Roy rosarinjroy at hotmail dot com
#
help_text = """
This script can be used similar to "perl -ne". See the examples below.
Example 1: Hello world
mypy 'print "Hello World"'
Example 2: Search for a pattern in the input file and print the line number and the line.
cat /tmp/input.txt | mypy -i re -n 'cre = re.compile("pattern"); \
m = cre.search(L);' 'if m != None: print NL, ":", L'
Example 3: Find the sum of a particular column in the input file.
$ cat /tmp/input.txt
x|1
y|2
z|3
$ cat /tmp/input.txt | mypy -i re -n --begin 'sum = 0' 'if len(L) == 0: continue' \
'f = L.split("|"); sum = sum + int(f[1]);' --end 'print sum'
6
"""
import argparse
import StringIO
import sys
prog_template = """%(imports)s
%(begin)s
%(prog)s
%(end)s"""
nested_prog_template = """%(imports)s
import sys
NL = 0
%(begin)s
for L in sys.stdin:
NL += 1
L = L.rstrip('\\n')
%(prog)s
%(end)s"""
# parser = argparse.ArgumentParser(description='Runs Python interpreter to the "perl -ne".', )
parser = argparse.ArgumentParser(formatter_class = argparse.RawDescriptionHelpFormatter, description= help_text)
parser.add_argument('-i', '--import', dest = 'imports', help = 'List of imports.')
parser.add_argument('--begin', dest = 'begin', help = 'Code to be executed only once at the beginning.')
parser.add_argument('-n', '--nest', dest = 'nest', action = 'store_true', help = 'Pass each line of stdin to the program. The line is available as L.')
parser.add_argument('prog', nargs = '+', help = 'Program to be executed.')
parser.add_argument('--end', dest = 'end', help = 'Code to be executed only once at the end.')
args = parser.parse_args()
if args.begin != None:
begin = args.begin
else:
begin = ''
if args.end != None:
end = args.end
else:
end = ''
if args.imports != None:
buff = StringIO.StringIO()
for y in args.imports.split(','):
y = y.strip()
if len(y) > 0:
buff.write('import ')
buff.write(y)
buff.write('\n')
imports = buff.getvalue()
else:
imports = ''
if args.nest:
prog_template = nested_prog_template
prog = '\n '.join(args.prog)
else:
prog = '\n'.join(args.prog)
prog = prog_template%({'imports': imports, 'begin': begin, 'prog': prog, 'end': end})
exec prog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment