Welcome, guest | Sign In | My Account | Store | Cart

A Python script that runs arbitrary Python scripts in an input loop. This allows one-liner Python scripts similarly to how Perl runs them (-l,-a,-n,-F, BEGIN, END)

It provides additional syntax that allows multiline Python scripts to be run on a single line

Python, 260 lines
  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
#!/usr/bin/env python

"""
Python script that runs one-liner python scripts similarly to how Perl runs them

portions based on http://code.activestate.com/recipes/437932-pyline-a-grep-like-sed-like-command-line-tool/
(Graham Fawcett, Jacob Oscarson, Mark Eichin)
interface inspired by Perl
"""

"""
Copyright (C) 2010  Drew Gulino

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys
import re
import getopt
from getopt import GetoptError
import os

def usage(progname):
    print "Usage: " + progname
    version()
    print """
    ./pyliner (options) "script"
    -a enables auto-split of input into the F[] array.
    -F specifies the characters to split on with the -a option (default=" ")
    -p loops over and prints input.
    -n loops over and does not print input.
    -l strips newlines on input, and adds them on output 
    -M lets you specify module imports
    -o print out parsed and indented script on multiple lines
    -e (assumed - does nothing, added for Perl compatibility)
    
    variables:
    F[] = split input
    line = current input line
    NR = current input line number
    
    functions:
    I(x) = function returns F[x] cast to integer
    f(x) = function returns F[x] cast to float
    
    script:
        newlines are specified with ";"
        ":" will start an indent for the following lines
        "?;" will add a newline and dedent the following lines
        "/;" will reset the indent the far left
        "BEGIN:" starts the an initial script not run in the input loop
        "END:" starts part of the script run after the input loop
        "#/" ends both the "BEGIN:" and "END:" portions of the script
    """

#test.txt=
"""
10,test
1,rest
100,test
10,best
1000,we
1,see
"""

"""
cat test.txt | ./pyline.py -F"," -lane 'BEGIN:sum=0#/if i(0) > 90:sum+=i(0)) END:print sum#/'
1100
"""

"""
pyliner:
cat test.txt | ./pyliner.py -F"," -lane 'BEGIN:sum=0#/a=f(0);if a > 90:sum+=a END:print sum/NR#/'
183.333333333

perl:
cat test.txt | perl -F"," -lane 'BEGIN {$sum=0; } ;$sum=$sum+=@F[0] if @F[0]>90;END { print $sum/$.; }'
183.333333333333
"""

def version():
    print "version: 1.0"

write = sys.stdout.write

def indent_script(script_lines):
    #indent lines
    indent = 0
    next_indent = 0
    script = []
    for cmd in script_lines:
        cmd = cmd.strip()
        if cmd[-1]==(":"):
            indent=indent+1
        if cmd[-1]=="?":
            cmd=cmd[0:-1]
            indent=indent-1
        if cmd[-1]=="/":
            cmd=cmd[0:-1]
            indent=0
        cmd=("\t"*next_indent)+cmd
        next_indent = indent
        script.append(cmd)
    script = '\n'.join(script)
    return script

def split_script(cmd):
    #split lines
    cmd = cmd.replace("?;","?\n")
    cmd = cmd.replace("/;","/\n")
    cmd = cmd.replace(";","\n")
    cmd = cmd.replace(":",":\n")
    return cmd

def main(argv, stdout, environ):
    progname = argv[0]
    split_lines=False
    FS = ' '
    print_input = False
    strip_newlines = False
    no_print_input = False
    output_script = False
    F =[]
    
    def I(x): return int(F[x])
    
    def f(x): return float(F[x])
    # parse options for module imports
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'oaplneM:F:')
    except GetoptError:
        print "Invalid Option!"
        usage(progname)
        return
    
    opts = dict(opts)
    if '-M' in opts:
        for imp in opts['-M'].split(','):
            locals()[imp] = __import__(imp.strip())
    if "-a" in opts:
        split_lines = True
    if '-F' in opts:
        FS = opts['-F']
    if "-p" in opts:
        print_input = True
    if "-l" in opts:
        strip_newlines = True
    if "-n" in opts:
        no_print_input = True
    if "-e" in opts:
        pass
    if "-o" in opts:
        output_script = True

    cmd = ' '.join(args)
    if not cmd.strip():
        cmd = 'line'                        # no-op
    
    begin_cmd = ''
    end_cmd = ''
    
    if cmd.find("BEGIN:") >= 0:
        start=cmd.find("BEGIN:")
        end=cmd.find("#/")
        begin_cmd=cmd[start+6:end]
        cmd=cmd[end+2:]
        
    if cmd.find("END:") >= 0:
        start=cmd.find("END:")
        end=cmd.find("#/")
        end_cmd=cmd[start+4:end]
        cmd=cmd[:start]
    
    cmd = split_script(cmd)
    script_lines = cmd.splitlines()
    
    if len(begin_cmd) > 1:
        begin_cmd = split_script(begin_cmd)
        begin_lines = begin_cmd.splitlines()
        begin_script = indent_script(begin_lines)
    
        begin_codeobj = compile(begin_script, 'command', 'exec')
        result =  eval(begin_codeobj, globals(), locals())
        if result is None or result is False:
            result = ''
        elif isinstance(result, list) or isinstance(result, tuple):
            result = ' '.join(map(str, result))
        else:
            result = str(result)
        write(result)
    
    
    if len(end_cmd) > 1:
        end_cmd = split_script(end_cmd)
        end_lines = end_cmd.splitlines()
        end_script = indent_script(end_lines)
        end_codeobj = compile(end_script, 'command', 'exec')
        
    script = indent_script(script_lines)
    
    if output_script == True:
        print "BEGIN:"
        print begin_script 
        print
        print script 
        print
        print "END:"
        print end_script 
        print
    
    #compile script   
    codeobj = compile(script, 'command', 'exec')
    
    if print_input or no_print_input:
        for num, line in enumerate(sys.stdin):
            #line = line[:-1]
            NR = num + 1
            if strip_newlines == True:
                line = line.strip()
            if print_input == True:
                print(line)
            if split_lines == True:
                F = [w for w in line.split(FS) if len(w)]
            result =  eval(codeobj, globals(), locals())
            if result is None or result is False:
                continue
            elif isinstance(result, list) or isinstance(result, tuple):
                result = ' '.join(map(str, result))
            else:
                result = str(result)
            write(result)
            if strip_newlines == True:
               write('\n')
    
    else:
        result =  eval(codeobj, globals(), locals())
        
    if len(end_cmd) > 1:    
        result =  eval(end_codeobj, globals(), locals())
        if result is None or result is False:
            result = ''
        elif isinstance(result, list) or isinstance(result, tuple):
            result = ' '.join(map(str, result))
        else:
            result = str(result)
        write(result)
    
if __name__ == "__main__":
    main(sys.argv, sys.stdout, os.environ)

I work on *nix systems and use one-liner bash+awk+sed+etc.. scripts all the time, but I find I need Perl for some features. But I prefer and remember Python better. There are a few other scripts that allow something like Perl's cool one-liner '-lane', 'BEGIN' ,'END', etc, but don't have the full functionality.

This script is based on http://code.activestate.com/recipes/437932-pyline-a-grep-like-sed-like-command-line-tool/ (Graham Fawcett + Jacob Oscarson, Mark Eichin) and Perl. It attempts to provide all the one-liner functionality that Perl provides.

To get this to work, I had to create some additional syntax to allow Python to run on a single line without tabs. I understand this goes against much of what Python 'stands' for, but I'm pragmatic. This is no PEP to modify the language or a critique of Python's syntax; I just like the language and want to use it in an area that it's not well adapted for.

pyliner (options) "script" -a enables auto-split of input into the F[] array. -F specifies the characters to split on with the -a option (default=" ") -p loops over and prints input. -n loops over and does not print input. -l strips newlines on input, and adds them on output -M lets you specify module imports -o print out parsed and indented script on multiple lines -e (assumed - does nothing, added for Perl compatibility)

variables: F[] = split input line = current input line NR = current input line number

functions: I(x) = function returns F[x] cast to integer f(x) = function returns F[x] cast to float

script: newlines are specified with ";" ":" will start an indent for the following lines "?;" will add a newline and dedent the following lines "/;" will reset the indent the far left "BEGIN:" starts the an initial script not run in the input loop "END:" starts part of the script run after the input loop "#/" ends both the "BEGIN:" and "END:" portions of the script

usage:

test.txt:

10,test
1,rest
100,test
10,best
1000,we
1,see

Example 1:

cat test.txt | ./pyline.py -F"," -lane 'BEGIN:sum=0#/if i(0) > 90:sum+=i(0)) END:print sum#/'

output:

1100

Example 2:

pyliner

cat test.txt | ./pyliner.py -F"," -lane 'BEGIN:sum=0#/a=f(0);if a > 90:sum+=a END:print sum/NR#/'

output:

183.333333333

perl:

cat test.txt | perl -F"," -lane 'BEGIN {$sum=0; } ;$sum=$sum+=@F[0] if @F[0]>90;END { print $sum/$.; }'

output:

183.333333333333

Example 3:

Chunk average (average of every N amount of numbers in a pipe):

echo -en "1\n 2\n 3\n 4\n 10\n 10\n 10\n 10\n" | ./pyliner.py -lane -F"," 'BEGIN:s=0;n=4#/s+=f(0);if not NR % n:print s/n;s=0'

output:

2.5
10.0

1 comment

Tim Chambers 9 years, 9 months ago  # | flag

-o didn't work for me so I created this patch:

diff --git a/scripts/pyliner b/scripts/pyliner
index 64d5adc..38f0076 100755
--- a/scripts/pyliner
+++ b/scripts/pyliner
@@ -91,7 +91,7 @@ cat test.txt | perl -F"," -lane 'BEGIN {$sum=0; } ;$sum=$sum+=@F[0] if @F[0]>90;
 """

 def version():
-    print "version: 1.0"
+    print "version: 1.1"

 write = sys.stdout.write

@@ -185,7 +185,9 @@ def main(argv, stdout, environ):

 cmd = split_script(cmd)
 script_lines = cmd.splitlines()
-
+    begin_script = ''
+    end_script = ''
+
 if len(begin_cmd) > 1:
     begin_cmd = split_script(begin_cmd)
     begin_lines = begin_cmd.splitlines()