Moving folders with content

Hans Mulder hansmu at xs4all.nl
Sun Sep 16 06:40:18 EDT 2012


On 16/09/12 10:02:09, jyoung79 at kc.rr.com wrote:
> Thank you  "Nobody" and Hans!

You're welcome!

>> You may want to use the subprocess module to run 'ditto'.  If
>> the destination folder does not exist, then ditto will copy MacOS
>> specific aspects such as resource forks, ACLs and HFS meta-data.
> 
> This looks like a good direction to go.  Maybe something like:
> 
>>>> import os
>>>> import subprocess
>>>>
>>>> p1 = os.path.expanduser('~/Desktop/IN/Test/')
>>>> p2 = os.path.expanduser('~/Desktop/OUT/Test/')
>>>>
>>>> cmd = 'ditto -vV "' + p1 + '" "' + p2 + '"'
>>>>
>>>> v = subprocess.check_output(cmd, shell=True)

This looks iffy: it would break if there would be any double
quotes in p1 or p2.  You might think that os.path.expanduser
would never expand '~' to something containing a double quote,
but you'd be wrong:

>>> import os
>>> os.environ['HOME'] = 'gotcha!"; rm -rf '
>>> print(os.path.expanduser('~/Desktop/IN/Test/'))
gotcha!"; rm -rf /Desktop/IN/Test/

It's easy and safer to avoid using 'shell=True' option:

cmd = ['ditto', '-vV', p1, p2]
v = subprocess.check_output(cmd, shell=False)

In this case, the safer version also happens to be shorter and
more readable.  But you should get into the habit of using
shell=False whenever possible, because it is much easier to
get it right.


Hope this helps,

-- HansM



More information about the Python-list mailing list