Sunday, 4 April 2010

Python one-line scripts

It's not so crazy as it could be with perl, but still weird with a little of functional magic:

to get the recurcive list of full-path-names under working directory:

python -c 'import os; print map(lambda x: os.sep.join(x), reduce(lambda x,y: x+y, map(lambda x: zip(*x), [((l[0],)*len(l[2]),l[2]) for l in os.walk(os.getcwd())])))'

python3 differs a little: there is no built-in reduce, map returns a map-object, not a list, print is a function.

python3 -c 'from functools import reduce; import os; print (list(map(lambda x: os.sep.join(x), reduce(lambda x,y: list(x)+list(y), map(lambda x: zip(*x), [((l[0],)*len(l[2]),l[2]) for l in os.walk(os.getcwd())])))))'

Now let's use it to get a list of dicts like {file name: md5}

python -c 'import hashlib, os; print map(lambda x: {x.name : hashlib.md5(x.read()).hexdigest()}, [open(f) for f in map(lambda x: os.sep.join(x), reduce(lambda x,y: x+y, map(lambda x: zip(*x), [((l[0],)*len(l[2]),l[2]) for l in os.walk(os.getcwd())])))])'

python3 -c 'from functools import reduce; import os,hashlib; print(list(map (lambda x: {x : hashlib.md5(open(x, "rb").read()).hexdigest()}, [f for f in filter(os.path.isfile, map(lambda x: os.sep.join(x), reduce(lambda x,y: list(x)+list(y), map(lambda x: zip(*x), [((l[0],)*len(l[2]),l[2]) for l in os.walk(os.getcwd())]))))])))'

No wonder, it works slower as the simlpest way as it a C-binary:md5sum `find . -type f`

P.S.Early I saw another one example of an 1-line gui(!) application:
type('', (__import__('wx').App,), dict(OnInit=lambda self:__import__('wx').Frame(None, -1, "Hello world!").Show(True)))(0).MainLoop()

(Needs wxpython, of course)





No comments:

Post a Comment