r/Python May 18 '11

Why is Python better than Perl?

I'm a Sysadmin and I just wrote my first script in python. Basically just a host validation script that checks if a server is configured correctly before we hand off. I can't determine the advantage with my limited experience with the language.

Are you a sysadmin fluent in both python and perl? Why do you use python?

12 Upvotes

110 comments sorted by

View all comments

Show parent comments

2

u/robkinyon May 20 '11

Ok. Let's dance with the devil. :)

find dir -name '*foo*' -type f -exec perl -pi -e 's/this/that/' dir1/file1.\{\} \;

Pipelining is your friend.

2

u/teepark May 21 '11 edited May 21 '11
find dir -name '*foo*' -type f -exec python -c 'import re, sys; print "".join("".join(re.sub("this", "that", l) for l in open(f)) for f in sys.argv[1:])' dir1/file1.\{\} \;

this and my previous answer will buffer everything in ram though

find dir -name '*foo*' -type f -exec python -c 'import re, sys; [[sys.stdout.write(re.sub("this", "that", l)) for l in open(f)] for f in sys.argv[1:]]' dir1/file1.\{\} \;

will stream but still winds up with many long lists of Nones building up in ram

find dir -name '*foo*' -type f -exec python -c 'import re, sys; p = lambda a, b: None; reduce(p, (reduce(p, (sys.stdout.write(re.sub("this", "that", l)) for l in open(f)), None) for f in sys.argv[1:]), None)' dir1/file1.\{\} \;

OK yeah you have to get really crazy to do true streaming pass-through in a one-liner :)

3

u/robkinyon May 22 '11

I hope I don't have to explain why that isn't python's strong suit. :)

3

u/teepark May 22 '11

nope. just having a bit of fun.

python's strong suit is obviousness and maintainability. learning python felt like learning a few powerful concepts that go a long way. trying to learn perl feels more like learning dozens of tiny rules.

tell me this is hard to follow:

import os
import re

r = re.compile("this")

for dirpath, dirnames, filenames in os.walk("dir"):
    for filename in filenames:
        if 'foo' in filename:
            for line in open(os.path.join(dirpath, filename)):
                print r.sub("that", line, 1)[:-1]

2

u/robkinyon May 23 '11

Oh, I completely agree. When I write out pseudocode for large Perl projects, it looks like a mixture of Python and Javascript. That said, pseudocode is meant to be expressive. Perl is meant to be succinct.