Revision 35 as of 2010-05-11 05:15:15

Clear message

Powerful Python One-Liners

This is a page that is devoted to short programs that can perform powerful operations. The ability to write short programs that are just as powerful as a program written in another language designed to do the same thing. However, it is sometimes fun to try and write a program in Python that is only one line. In other languages this would be nearly impossible, but in Python it is a lot easier to do. The trick is to think up something that will "do a lot with a little." I, personally, would love to see this page expanded to the point where it needs some sort of organization system.

Thanks for Your Code, JAM

Contributed Code


Some thoughts by ewo:

import pprint;pprint.pprint(zip(('Byte', 'KByte', 'MByte', 'GByte', 'TByte'), (1 << 10*i for i in xrange(5))))

print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j*8, 256**j-1) for j in (1 << i for i in xrange(8)))

Cute, isn't it?

Set of all subsets

f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j & 1)] for i in range(2**len(set(x)))]


>>>f([10,9,1,10,9,1,1,1,10,9,7])
[[], [9], [10], [9, 10], [7], [9, 7], [10, 7], [9, 10, 7], [1], [9, 1], [10, 1], [9, 10, 1], [7, 1], [9, 7, 1], [10, 7, 1], [9, 10, 7, 1]]

-RJW

Decode a base64 encoded file

import base64, sys; base64.decode(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))

Editing a list of files in place

I came up with this one-liner in response to an article that said it couldn't be done as an one-liner in Python.

What this does is replace the substring "at" by "op" on all lines of all files (in place) under the path specified (here, the current path).

   1 import sys,os,re,fileinput;a=[i[2] for i in os.walk('.') if i[2]] [0];[sys.stdout.write(re.sub('at','op',j)) for j in fileinput.input(a,inplace=1)]

Clearer is: import os.path; a=[f for f in os.listdir('.') if not os.path.isdir(f)]

Reimplementing cut

Print every line from an input file but remove the first two fields.

python -c "import sys;[sys.stdout.write(' '.join(line.split(' ')[2:])) for line in sys.stdin.read().splitlines(True)]" < input.txt 

Cramming Python into Makefiles

A related issue is embedding Python into a Makefile. I had a really long script that I was trying to cram into a makefile so I automated the process:

import sys,re

def main():
    fh = open(sys.argv[1],'r')
    lines = fh.readlines()
    print '\tpython2.2 -c "`printf \\"if 1:\\n\\'
    for line in lines:
        line = re.sub('[\\\'\"()]','\\\g<0>',line)
        # grab leading white space (should be multiples of 4) and makes them into
        # tabs
        wh_spc_len = len(re.match('\s*',line).group())
        
        sys.stdout.write('\t')
        sys.stdout.write(wh_spc_len/4*'\\t'+line.rstrip().lstrip())
        sys.stdout.write('\\n\\\n')
    print '\t\\"`"'

if __name__=='__main__':
    main()

This script generates a "one-liner" from make's point of view.

echo unicode character:

python -c "print unichr(234)"

This script echo "ê"

Apply regular expression to lines from stdin

[another command] | python -c "import sys,re;[sys.stdout.write(re.compile('PATTERN').sub('SUBSTITUTION', line)) for line in sys.stdin]"

Display List of all users on Unix like system

[ line[:-1].split(":")[0] for line in open("/etc/passwd").readline() ]

Unable to edit the page? See the FrontPage for instructions.