Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python oggenc script

Tags:

python

I want to write a python script (Yes not Bash) that will use flac files and encode them using oggenc and then on successful encoding delete the flac file.

So far I have this:

import os, sys
import fnmatch

command = 'oggenc -q7 *.flac'

def main():
    for root, dirs, files in os.walk('/home/wagnerf/test'):
        for name in files:
            if fnmatch.fnmatch(name, '*.flac'):

I kind of wanted to use

os.system("bash -c %s" % command)

after the if but that won't work, say's

ERROR: No input files specified. Use -h for help.

I guess I have to use the name in my command?

EDIT My file structure will look somethibg like this:

-- test
   -- test1
     -- test1.flac
     -- test2.flac
   -- test2
     -- test3.flac
     -- test1.flac

And I want those flac files to be converted to ogg in the same directory, basically I want to automate

cd /somedir/
oggenc -q7 *.flac
cd ..
cd /someotherdir/
oggenc -q7 *.flac

so that I don't have to always enter the subdirectory!

ANSWER:

@larsmanns Thank you very much, just had to make some adjustments:

from fnmatch import fnmatch
import os, sys
import subprocess

def main():
    for root, dirs, files in os.walk('/home/wagnerf/test'):
        flacs = [f for f in files if fnmatch(f, '*.flac')]
        if flacs:
            for file in flacs:
                cmd = 'oggenc', '-q7', '%s' % file
                subprocess.check_call(cmd, cwd=root)

flacs returns a list and we need to use oggenc per file so for every tuple do ... Anyway thanks again the rest is easy!

BTW

I finished the script you can find it here: musico

like image 875
wagner-felix Avatar asked Feb 18 '26 09:02

wagner-felix


1 Answers

Use the subprocess module to call external commands, that offers more detailed control:

from fnmatch import fnmatch
import os
import subprocess

def main():
    for root, dirs, files in os.walk('/home/wagnerf/test'):
        flacs = [f for f in files if fnmatch(f, '*.flac')]
        for f in flacs:
            cmd = ['oggenc', '-q7', f]
            subprocess.check_call(cmd, cwd=root)

The cwd keyword argument changes to the specified directory before executing the command. The globbing (filename pattern matching) is already done by fnmatch, so there's need to call a shell in between.

You can delete a file with os.remove; I haven't put that in the example yet. Also, the above snippet is untested.

like image 117
Fred Foo Avatar answered Feb 19 '26 21:02

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!