#!/usr/bin/python # #jmeb @ May 2011 #A very first attempt at python scripting # #Automate various conversions between ebook formats # #TODO: # import os import subprocess import sys import datetime import argparse def main(): #List of available formats to convert formats = [ 'epub','mobi','html','lit', 'rtf', 'txt', 'odt' ] #Parse command line arguments ap = argparse.ArgumentParser(description='Batch convert between ebook formats.') ap.add_argument('--have', action='store', default='epub', choices=formats) ap.add_argument('--want', action='store', default='mobi', choices=formats) ap.add_argument('-s', '--src', default=os.getcwd()) ap.add_argument('-d', '--dst', default=os.getcwd()) args = ap.parse_args() #Switch dirs to absolute paths src = os.path.abspath(args.src) dst = os.path.abspath(args.dst) #Add period and string-ify things to be safe have = "." + str(args.have) want = "." + str(args.want) #Get the two lists of files, sans extensions froms = [ fn[:-len(have)] for fn in os.listdir(src) if fn.endswith(have)] tos = [ fn[:-len(want)] for fn in os.listdir(dst) if fn.endswith(want)] #Compare the two lists converts = [ convert for convert in froms if convert not in tos ] #Generate bash-friendly list to run conversion ebooks = [] for convert in converts: fromfile = src + '/"' + convert + have + '" ' tofile = dst + '/"' + convert + want + '" ' ebook = 'ebook-convert ' + fromfile + tofile ebooks.append(ebook) #Run the conversion for ebook in ebooks: subprocess.call(ebook, shell=True) #Log things if necessary if len(converts) > 0: os.chdir(src) Log = open('ConversionLog.txt', 'a') now = datetime.datetime.now() Log.write('\n' + 'Converted to ' + want + ' at ' + str(now) + '\n') for convert in converts: Log.write(convert + '\n') Log.close() if __name__ == '__main__': main()