LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how do I do this in Python? (simple sh script) (https://www.linuxquestions.org/questions/programming-9/how-do-i-do-this-in-python-simple-sh-script-269267/)

johnMG 12-22-2004 02:12 PM

how do I do this in Python? (simple sh script)
 
I recently had to convert a directory full of source files from dos-style to normal unix-style line endings. I ended up dashing off a simple bash script, something like:
Code:

#!/bin/bash

for file in *.{cpp,h,hpp}
do
    dosunix $file XXX.newfile
    rm $file
    mv XXX.newfile $file
done

This wasn't ideal, since I had to manually cd into various subdirectories and run it again from there.

(Also note that dosunix is the dos2unix available via fink on Mac OS X).

I'm learning Python ATM, and am curious: how could I have done this in Python? (Once I get this simple version working, I think the really fun part will be getting it to recursively traverse subdirectories and hit 'em all. :)

sigsegv 12-22-2004 02:43 PM

I believe os.walk is the method you're looking for for drilling down a directory.

Tinkster 12-22-2004 03:21 PM

Another non-python solution would have been:

Code:

save as helper.sh
dosunix $1 XXX.newfile
rm $1
mv XXX.newfile $1

chmod that and put somewhere in path ...

Code:

find \( -iname "*.h" -o -iname "*.cpp" -o -iname "*.hpp" \) -exec helper.sh {} \;

Cheers,
Tink

johnMG 12-22-2004 04:10 PM

sigsegv, thanks for the great hint.

Now, how do I run dosunix on each item in a list of filenames (once I get that list via os.walk)?

Code:

#!/usr/bin/python
#...
for file in list_of_files:
    floob( 'dosunix', file, 'XXX.newfile' )
    floob( 'rm', file )
    floob( 'mv', 'XXX.newfile', file )

Tink -- thanks for the alternative.

Hko 12-22-2004 06:14 PM

I'm a newbie in python, so this may not be very optimal. But it works for me.
Also I think it would be nicer to do the dos-unix conversion in python as well.
Code:

#!/usr/bin/env python

import os

for root, dirs, files in os.walk('/your/directory'):
    for name in files:
        if os.path.splitext(name)[1] in ['.h', '.cpp', '.hpp']:
            file = os.path.join(root, name)
            temp = file + '.tmp'
            os.system('dosunix ' + file + ' ' + temp)
            os.rename(temp, file)


Hko 12-22-2004 06:25 PM

A bash script that goes through all subdirectories:
Code:

#!/bin/bash

find -type f -regex '.*\.cpp\|.*\.h\|.*\.hpp' | while read F ; do
        dosunix $F ${F}.tmp
        mv ${F}.tmp $F
done


johnMG 12-22-2004 10:05 PM

Ahh... os.system().

I just found commands.getoutput( 'some_command' ).

Hmm... looks like you use commands.getoutput() when you want to save the return value into a variable, and you use os.system() when you want the output going to the console.

Sweet! Thanks.


All times are GMT -5. The time now is 02:09 AM.