Thursday, September 22, 2011

Where is that missing recursive chown for Python

A question from a colleague of mine prompted me on a week long search for a recursive chown for Python. Initially I just thought that it was due to his inexperience that he was unable to find an answer as a recursive chown sounds too easy of a function for Python not to have. Alas, however after on and off scouring the net I found that the closest (and the best) answer to what he was looking for is actually This stack overflow question. Ruby has their built into the Fileutils library which really prompted this post. Also on a less cursory glance I notice that the ruby standard lib has some functions which I really wished Python has which would make a probably transition from my bunch of work horse bash script to a Ruby platform that much easier. They have cp, cp_r and even a diff! Nice! Has there been any attempt of making this easier in Python? If someone knows better please enlighten me, as this just seems too easy for Python not to have.

4 comments:

Pedahzur said...

def recur_chown(starting_dir, uid, gid):
for root, dirs, files in os.walk(starting_dir):
os.chown(os.path.join(starting_dir, root), uid, gid)
for f in files:
os.chown(os.path.join(starting_dir, root, f), uid, gid)

Five lines of Python, not tested (although the white space and wrapping probably didn't come through properly). There are much more complex things that could be arguably made "built ins." Not sure that function is one of them.

ΤΖΩΤΖΙΟΥ said...

import shutil

shutil.copyfile for cp
shutil.copytree for cp_r

and then there is difflib.

Petri Lehtinen said...

Recursive chown was discussed a while back on python-dev mailing list here.

An issue was never opened, though, so maybe you should open one?

lowks said...

I have created a report for this. Thanks Petri for the link.

http://bugs.python.org/msg144439