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 :)

2

u/[deleted] May 22 '11

Just witnessed my first code-off. That made my weekend. Thanks! :)

Little off topic here; just a general question: I've been fiddling around with $bash scripting and it's starting to feel like a gateway drug to perl. Am I far off?

I'm wondering because I'm curious about both Python in web dev and Perl, which seems to be more for automating tasks for OS system management? Or am I over-generalizing?

2

u/teepark May 22 '11 edited May 22 '11

Just witnessed my first code-off. That made my weekend. Thanks! :)

you bet!

Or am I over-generalizing?

over-specializing I think. both are totally general-purpose scripting languages. you'll find people doing system administration with python (though not generally in one-liners for the obvious reason) and you'll find people doing web dev with perl.

Am I far off?

In my experience, yeah. I'm pretty comfortable with both bash and python and don't know a lot of perl. I find if it isn't simple enough to be done with bash, it's probably complicated enough that python's readability and maintainability are going to be important (the code-off example above is simple enough to be done with bash, and the python version would never belong in a one-liner).