使用Python对文件夹中的每个文件执行命令

发布于 2024-07-27 01:03:55 字数 1582 浏览 10 评论 0原文

我正在尝试创建一个Python脚本,该脚本将:

  1. 查看文件夹“/input”
  2. 对于该文件夹中的每个视频,运行mencoder命令(将它们转码为可在我的手机上播放的内容)
  3. mencoder完成运行后,删除原始视频。

这看起来不太难,但我对 python 很烂:)

关于脚本应该是什么样子有什么想法吗?

额外问题:我应该使用

操作系统

子进程.call

.调用?

Subprocess.call 似乎允许使用更具可读性的脚本,因为我可以编写如下命令:

cmdLine = ['mencoder', 源视频, '-ovc', '复制', '-oac', '复制', '-ss', '00:02:54', '-endpos', '00:00:54', '-o', 目的地视频]

编辑:好的,可行:

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')

为了清楚起见,我已经删除了 mencoder 命令,因为我仍在研究它。

感谢大家的意见。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

趴在窗边数星星i 2024-08-03 01:03:55

要查找所有文件名,请使用 os.listdir()。

然后循环文件名。 像这样:

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

如果您喜欢子流程,请使用子流程。 :-)

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. :-)

屌丝范 2024-08-03 01:03:55

使用 os.walk 递归地迭代目录内容:

import os

root_dir = '.'

for directory, subdirectories, files in os.walk(root_dir):
    for file in files:
        print os.path.join(directory, file)

之间没有真正的区别os.system 和 subprocess.call 在这里 - 除非你必须处理奇怪命名的文件(文件名包括空格、引号等)。 如果是这种情况, subprocess.call 肯定更好,因为您不需要对文件名进行任何 shell 引用。 当您需要接受任何有效的 shell 命令时,例如从配置文件中的用户接收到的命令,os.system 会更好。

Use os.walk to iterate recursively over directory content:

import os

root_dir = '.'

for directory, subdirectories, files in os.walk(root_dir):
    for file in files:
        print os.path.join(directory, file)

No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

め可乐爱微笑 2024-08-03 01:03:55

Python3中新的推荐方式是使用 pathlib

from pathlib import Path

mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
    print(file.name)
    # do your stuff

除了 *.mp4,您可以使用任何过滤器,甚至是像 **/*.mp4 这样的递归过滤器。 如果您想使用多个扩展名,您可以简单地使用 ***/* (递归)迭代所有文件,并使用 file 检查每个文件的扩展名。 name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))

The new recommend way in Python3 is to use pathlib:

from pathlib import Path

mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
    print(file.name)
    # do your stuff

Instead of *.mp4 you can use any filter, even a recursive one like **/*.mp4. If you want to use more than one extension, you can simply iterate all with * or **/* (recursive) and check every file's extension with file.name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))

云之铃。 2024-08-03 01:03:55

Python 对此可能有些过分了。

for file in *; do mencoder -some options "$file"; rm -f "$file" ; done

rm -f "$file" 删除文件。

Python might be overkill for this.

for file in *; do mencoder -some options "$file"; rm -f "$file" ; done

The rm -f "$file" deletes the files.

月竹挽风 2024-08-03 01:03:55

AVIMPG(选择您的扩展名):

files = os.listdir('/input')
for sourceVideo in files:
    if sourceVideo[-4:] != ".avi"
        continue
    destinationVideo = sourceVideo[:-4] + ".mpg"
    cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
        '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
    output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
    print output1
    output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
    print output2

AVI to MPG (pick your extensions):

files = os.listdir('/input')
for sourceVideo in files:
    if sourceVideo[-4:] != ".avi"
        continue
    destinationVideo = sourceVideo[:-4] + ".mpg"
    cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
        '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
    output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
    print output1
    output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
    print output2
栩栩如生 2024-08-03 01:03:55

或者你可以使用 os.path.walk 函数,它比 os.walk 为你做更多的工作:

一个愚蠢的例子:

def walk_func(blah_args, dirname,names):
    print ' '.join(('In ',dirname,', called with ',blah_args))
    for name in names:
        print 'Walked on ' + name

if __name__ == '__main__':
    import os.path
    directory = './'
    arguments = '[args go here]'
    os.path.walk(directory,walk_func,arguments)

Or you could use the os.path.walk function, which does more work for you than just os.walk:

A stupid example:

def walk_func(blah_args, dirname,names):
    print ' '.join(('In ',dirname,', called with ',blah_args))
    for name in names:
        print 'Walked on ' + name

if __name__ == '__main__':
    import os.path
    directory = './'
    arguments = '[args go here]'
    os.path.walk(directory,walk_func,arguments)
娇纵 2024-08-03 01:03:55

我遇到了类似的问题,在网络上得到了很多帮助,在这篇文章中我做了一个小应用程序,我的目标是 VCD 和 SVCD,我不会删除源代码,但我认为适应你自己的源代码会相当容易需要。

它可以转换 1 个视频并剪切它,或者可以转换文件夹中的所有视频,重命名它们并将它们放入子文件夹 /VCD

我还添加了一个小界面,希望其他人觉得它有用!

我将代码和文件放在这里顺便说一句: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.

It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD

I also add a small interface, hope someone else find it useful!

I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文