Advertisement
Guest User

jmeb

a guest
Jul 8th, 2011
1,716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. #!/usr/bin/python
  2. #
  3. #jmeb @ May 2011
  4. #A very first attempt at python scripting
  5. #
  6. #Automate various conversions between ebook formats
  7. #
  8. #TODO:
  9. #
  10.  
  11. import os
  12. import subprocess
  13. import sys
  14. import datetime
  15. import argparse
  16.  
  17. def main():
  18.  
  19.   #List of available formats to convert
  20.   formats = [
  21.             'epub','mobi','html','lit',
  22.             'rtf', 'txt', 'odt'
  23.             ]
  24.  
  25.   #Parse command line arguments
  26.   ap = argparse.ArgumentParser(description='Batch convert between ebook formats.')
  27.   ap.add_argument('--have', action='store', default='epub', choices=formats)
  28.   ap.add_argument('--want', action='store', default='mobi', choices=formats)
  29.   ap.add_argument('-s', '--src', default=os.getcwd())
  30.   ap.add_argument('-d', '--dst', default=os.getcwd())
  31.   args = ap.parse_args()
  32.  
  33.   #Switch dirs to absolute paths
  34.   src = os.path.abspath(args.src)
  35.   dst = os.path.abspath(args.dst)
  36.  
  37.   #Add period and string-ify things to be safe
  38.   have = "." + str(args.have)
  39.   want = "." + str(args.want)
  40.  
  41.   #Get the two lists of files, sans extensions
  42.   froms = [ fn[:-len(have)] for fn in os.listdir(src) if fn.endswith(have)]
  43.   tos = [ fn[:-len(want)] for fn in os.listdir(dst) if fn.endswith(want)]
  44.  
  45.   #Compare the two lists
  46.   converts = [ convert for convert in froms if convert not in tos ]
  47.  
  48.   #Generate bash-friendly list to run conversion
  49.   ebooks = []
  50.   for convert in converts:
  51.     fromfile =  src + '/"' + convert + have + '" '
  52.     tofile = dst + '/"' + convert + want + '" '
  53.     ebook = 'ebook-convert ' + fromfile + tofile
  54.     ebooks.append(ebook)
  55.  
  56.   #Run the conversion
  57.   for ebook in ebooks:
  58.     subprocess.call(ebook, shell=True)
  59.  
  60.   #Log things if necessary
  61.   if len(converts) > 0:
  62.     os.chdir(src)
  63.     Log = open('ConversionLog.txt', 'a')
  64.     now = datetime.datetime.now()
  65.     Log.write('\n' + 'Converted to ' + want + ' at ' + str(now) + '\n')
  66.     for convert in converts:
  67.       Log.write(convert + '\n')
  68.     Log.close()
  69.  
  70. if __name__ == '__main__':
  71.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement