python自动化ffmpeg从上传目录转换 [英] python automate ffmpeg conversion from upload directory

查看:183
本文介绍了python自动化ffmpeg从上传目录转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完成的上传脚本。但是,我需要弄清楚如何制作一个脚本,我可以在python中作为一个守护进程运行,以处理转换部分,并将转换的文件移动到最后的安装位置。继承我目前为止的目录观察者脚本:

 #/ usr / bin / python 

import os
import pyinotify import WatchManager,Notifier,ThreadedNotifier,ProcessEvent,EventCodes
import sys,time,syslog,config
from os import system
from daemon import Daemon

class myLog(ProcessEvent):
def process_IN_CREATE(self,event):
syslog.syslog(creation:+ event.pathname)
def process_IN_DELETE(self,事件)
syslog.syslog(delete:+ event.pathname)
def process_default(self,event):
syslog.syslog(default:+ event.pathname)

class MyDaemon(Daemon):
def loadConfig(self):
加载用户配置文件$
self.config = {}
self.parser = ConfigParser.ConfigParser()
如果不是os.path.isfile(self.configfile):
self.parser.write(open(self.configfile,'w'))
self.parser.readfp(open(self.configfile,'r'))

variables = {\
'mplayer':['路径',self.findProgram(mplayer)],\
'mencoder':['路径',self.findProgram(mencoder)] ,\
'tcprobe':['paths',self.findProgram(tcprobe)],\
'transcode':['paths',self.findProgram(transcode)] ,\
'ogmmerge':['paths',self.findProgram(ogmmerge)],\
'outputdir':['paths',os.path.expanduser(〜 )],\
}

for variables.keys():
self.cautiousLoad(variables [key] [0],key,variables [key] [

def cautiousLoad(self,section,var,default):
在一个异常子句中加载一个可配置的变量,
在变量未配置的情况下文件
try:
self.config [var] = int(self.parser.get(section,var))
除了:
self.config [var] = default
try:
self.parser.set(section,var,default)
除了:
self.parser.add_secti on(section)
self.parser.set(section,var,default)
self.parser.write(open(self.configfile,'w'))


def findProgram(self,program):
在路径中查找程序,如果在config.paths中找到路径,则返回完整路径:
如果os .path.isfile(os.path.join(path,program)):
返回os.path.join(路径,程序)
self.ui_configError(程序)

def run(self)
syslog.openlog('mediaConvertor',syslog.LOG_PID,syslog.LOG_DAEMON)
syslog.syslog('daemon started,enter loop')
wm = WatchManager )
mask = IN_DELETE | IN_CREATE
通知程序= ThreadedNotifier(wm,myLog())
通知程序()
wdd = wm.add_watch(self.config ['outputdir'],mask,rec = True)
while True:
time.sleep(1)
wm.rm_watch(wdd.values())
notifier.stop()
syslog.syslog
syslog.closelog()

如果__name__ ==__main__:
守护进程= MyDaemon('/ tmp / mediaconvertor.pid')
if len(sys.argv)== 2:
如果'start'== sys.argv [1]:
daemon.run()
如果'stop'== sys.argv [ 1]:
daemon.stop()
如果'restart'== sys.argv [1]:
daemon.restart()
else:
print未知命令
sys.exit(2)
sys.exit(0)
else:
print用法:%s start | stop | restart%sys.argv [ 0]
sys.exit(2)

不知道从这里去哪里。 / p>

解决方案

我不运行在Linux上,从来没有使用过的inotify功能在这里使用我会描述我将如何做一般的事情。



在最简单的情况下,您需要检查upload目录中是否有新文件,当有一个文件时,开始进行转换通知。



要检查是否有新文件可以执行以下操作:

  import os 
import time

def watch_directory(dirname =。):
old_files = set(os.listdir(dirname))
while 1:
time.sleep(1)
new_files = set(os.listdir(dirname))
diff = new_files - old_files
如果diff:
打印新文件,diff
old_files = new_files

watch_directory()

您可以通过首先对目录进行统计来查看是否有任何更改来最小化某些文件系统开销。

  def watch_directory(dirname =。):
old_files = set(os.listdir(dirname))
old_stat = os.stat(dirn ame)
而1:
time.sleep(1)
new_stat = os.stat(dirname)
如果new_stat == old_stat:
continue
new_files = set(os.listdir(dirname))
diff = new_files - old_files
如果diff:
打印新文件,diff
old_stat = new_stat
old_files = new_files

使用inotify,我认为这一切都为您处理,您将代码放入process_IN_CREATE )在新的文件可用时被调用。



有点棘手 - 观察者如何知道上传完成?如果通过上传部分取消上传,会发生什么?这可以像使web服务器做一个rename()在上传期间使用一个扩展名,另一个扩展名完成时一样简单。



一旦你知道文件,使用子进程.Popen(conversion_program,new_filename)或os.system(conversion_program new_filename&)可以在进行转换的新进程中产生转换。您需要处理像错误报告这样的内容,就像输入的格式不正确一样。它也应该清理,这意味着一旦转换完成,它应该从输入文件中删除。这可能与删除文件一样简单。



您还需要担心重新启动任何被杀死的转换。如果机器停机,重新启动的观察者如何知道哪些数据文件转换也被杀死并需要重新启动。但这可能是手动步骤。


I have a upload script done. But i need to figure out how to make a script that I can run as a daemon in python to handle the conversion part and moving the file thats converted to its final resting place. heres what I have so far for the directory watcher script:

 #!/usr/bin/python

import os
import pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventCodes
import sys, time, syslog, config
from os import system
from daemon import Daemon

class myLog(ProcessEvent):
 def process_IN_CREATE(self, event):
  syslog.syslog("creating: " + event.pathname)
 def process_IN_DELETE(self, event):
  syslog.syslog("deleting: " + event.pathname)
 def process_default(self, event):
  syslog.syslog("default: " + event.pathname)

class MyDaemon(Daemon):
 def loadConfig(self):
  """Load user configuration file"""
  self.config = {}
  self.parser = ConfigParser.ConfigParser()
  if not os.path.isfile(self.configfile):
   self.parser.write(open(self.configfile, 'w'))
  self.parser.readfp(open(self.configfile, 'r'))

  variables = { \
   'mplayer':  ['paths', self.findProgram("mplayer")], \
   'mencoder':  ['paths', self.findProgram("mencoder")], \
   'tcprobe':  ['paths', self.findProgram("tcprobe")], \
   'transcode':  ['paths', self.findProgram("transcode")], \
   'ogmmerge':  ['paths', self.findProgram("ogmmerge")], \
   'outputdir':  ['paths', os.path.expanduser("~")], \
   }

  for key in variables.keys():
   self.cautiousLoad(variables[key][0], key, variables[key][1])

 def cautiousLoad(self, section, var, default):
  """Load a configurable variable within an exception clause,
  in case variable is not in configuration file"""
  try:
   self.config[var] = int(self.parser.get(section, var))
  except:
   self.config[var] = default
   try:
    self.parser.set(section, var, default)
   except:
    self.parser.add_section(section)
    self.parser.set(section, var, default)
   self.parser.write(open(self.configfile, 'w'))


 def findProgram(self, program):
  """Looks for program in path, and returns full path if found"""
  for path in config.paths:
   if os.path.isfile(os.path.join(path, program)):
    return os.path.join(path, program)
  self.ui_configError(program)

 def run(self):
  syslog.openlog('mediaConvertor', syslog.LOG_PID,syslog.LOG_DAEMON)
  syslog.syslog('daemon started, entering loop')
  wm = WatchManager()
  mask = IN_DELETE | IN_CREATE
  notifier = ThreadedNotifier(wm, myLog())
  notifier.start()
  wdd = wm.add_watch(self.config['outputdir'], mask, rec=True)
  while True:
   time.sleep(1)
  wm.rm_watch(wdd.values())
  notifier.stop()
  syslog.syslog('exiting media convertor')
  syslog.closelog()

if __name__ == "__main__":
 daemon = MyDaemon('/tmp/mediaconvertor.pid')
 if len(sys.argv) == 2:
  if 'start' == sys.argv[1]:
   daemon.run()
  if 'stop' == sys.argv[1]:
   daemon.stop()
  if 'restart' == sys.argv[1]:
   daemon.restart()
  else:
   print "Unknown Command"
   sys.exit(2)
  sys.exit(0)
 else:
  print "Usage: %s start|stop|restart" % sys.argv[0]
  sys.exit(2)

not sure where to go from here.

解决方案

I don't run on Linux and have never used the inotify capabilities you are using here. I'll describe how I would do things generically.

In the simplest case, you need to check if there's a new file in the upload directory and when there is one, start doing the conversion notification.

To check if there are new files you can do something like:

import os
import time

def watch_directory(dirname="."):
    old_files = set(os.listdir(dirname))
    while 1:
        time.sleep(1)
        new_files = set(os.listdir(dirname))
        diff = new_files - old_files
        if diff:
            print "New files", diff
        old_files = new_files

watch_directory()

You may be able to minimize some filesystem overhead by first stat'ing the directory to see if there are any changes.

def watch_directory(dirname="."):
    old_files = set(os.listdir(dirname))
    old_stat = os.stat(dirname)
    while 1:
        time.sleep(1)
        new_stat = os.stat(dirname)
        if new_stat == old_stat:
            continue
        new_files = set(os.listdir(dirname))
        diff = new_files - old_files
        if diff:
            print "New files", diff
        old_stat = new_stat
        old_files = new_files

With inotify I think this is all handled for you, and you put your code into process_IN_CREATE() which gets called when a new file is available.

One bit of trickiness - how does the watcher know that the upload is complete? What happens if the upload is canceled part-way through uploading? This could be as simple as having the web server do a rename() to use one extension during upload and another extension when done.

Once you know the file, use subprocess.Popen(conversion_program, "new_filename") or os.system("conversion_program new_filename &") to spawn off the conversion in a new process which does the conversion. You'll need to handle things like error reporting, as when the input isn't in the right format. It should also clean up, meaning that once the conversion is done it should remove the input file from consideration. This might be as easy as deleting the file.

You'll also need to worry about restarting any conversions which were killed. If the machine does down, how does the restarted watcher know which data file conversions were also killed and need to be restarted. But this might be doable as a manual step.

这篇关于python自动化ffmpeg从上传目录转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆