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("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)

不知道从这里去哪里.

解决方法:

我不在Linux上运行,也从未使用过此处使用的inotify功能.我将描述我将如何做一般事情.

在最简单的情况下,您需要检查上载目录中是否有新文件,如果有,请开始执行转换通知.

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

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

您可以通过首先统计目录以查看是否有任何更改,来最大程度地减少一些文件系统的开销.

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

我认为使用inotify可以解决所有问题,并将代码放入process_IN_CREATE()中,当有新文件可用时,该代码将被调用.

有点棘手-观察者如何知道上传已完成?如果上传过程中途取消上传,会发生什么情况?这可能很简单,就像让Web服务器在上载期间使用一个扩展名并在完成时使用另一个扩展名来进行一个rename().

知道文件后,请使用subprocess.Popen(conversion_program,“ new_filename”)或os.system(“ conversion_program new_filename&”)在进行转换的新进程中产生转换.当输入的格式不正确时,您需要处理错误报告之类的事情.它还应该清理,这意味着一旦完成转换,就应从考虑中删除输入文件.这可能和删除文件一样容易.

您还需要担心重新启动所有被终止的转换.如果计算机出现故障,重新启动的观察程序如何知道哪些数据文件转换也被终止并需要重新启动.但这可以作为手动步骤来实现.

上一篇:rsync+inotify实时同步


下一篇:在Linux中观看文件中的更改