Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

foreach - Using Python to execute a command on every file in a folder

I'm trying to create a Python script that would :

  1. Look into the folder "/input"
  2. For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)
  3. Once mencoder has finished his run, delete the original video.

That doesn't seem too hard, but I suck at python :)

Any ideas on what the script should look like ?

Bonus question : Should I use

os.system

or

subprocess.call

?

Subprocess.call seems to allow for a more readable script, since I can write the command like this :

cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss', '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]

EDIT : Ok, that works :

import os, subprocess

bitrate = '100'
mencoder = 'C:\Program Files\_utilitaires\MPlayer-1.0rc2\mencoder.exe'
inputdir = 'C:\Documents and Settings\Administrator\Desktop\input'
outputdir = 'C:\Documents and Settings\Administrator\Desktop\output'

for fichier in os.listdir(inputdir):
    print 'fichier :' + fichier
    sourceVideo = inputdir + '\' + fichier
    destinationVideo = outputdir + '\' + fichier[:-4] + ".mp4"

    commande = [mencoder,
               '-of',
               'lavf',
               [...]
               '-mc',
               '0',

               sourceVideo,
               '-o',
               destinationVideo]

    subprocess.call(commande)

os.remove(sourceVideo)
raw_input('Press Enter to exit')

I've removed the mencoder command, for clarity and because I'm still working on it.

Thanks to everyone for your input.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To find all the filenames use os.listdir().

Then you loop over the filenames. Like so:

import os
for filename in os.listdir('dirname'):
     callthecommandhere(blablahbla, filename, foo)

If you prefer subprocess, use subprocess. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...