使用Python对文件夹中的每个文件执行命令 [英] Using Python to execute a command on every file in a folder
问题描述
- 查看文件夹/ input
- 对于该文件夹中的每个视频,运行mencoder命令(将其转码为可在手机上播放的内容)。
- mencoder完成运行后,删除原始视频。
这看起来不是太难,但我吮吸python:)
$ p
$ b pre
$ b $ p
$ p
$ p
$ b
os.system
或
subprocess.call
?
子流程。调用似乎允许更可读的脚本,因为我可以这样写命令:
lockquote
cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]
编辑:好的,工作:
import os,subprocess
bitrate ='100'
mencoder ='C:\\程序文件\_utilitaires\\MPlayer-1.0rc2\\\mencoder.exe'
inputdir ='C:\\Documents and Settings\\Administrator\\Desktop\\input '
outputdir ='C:\\ Documents and Settings\\Administrator\\Desktop\\\output'
用于os.listdir中的fichier(inputdir) :
print'fichier:'+ fichier
sourceVideo = inputdir +'\\'+ fichier
destinationVideo = outputdir +'\\'+ fichier [: - 4] + .mp4
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
源视频,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Enter Enter to exit')
为了清晰起见,我删除了mencoder命令
感谢大家的意见。 解决方案使用 os.listdir()
。
找到所有文件名文件名。像这样:
在os.listdir('dirname')中输入os
作为文件名:
callthecommandhere (blablahbla,filename,foo)
如果您喜欢子流程,请使用子流程。 : - )
I'm trying to create a Python script that would :
- Look into the folder "/input"
- For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)
- 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.
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. :-)
这篇关于使用Python对文件夹中的每个文件执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!