Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.62 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. """
  4. pyltx is a script with some useful tools to working with LaTeX.
  5. Run "pyltx -h" to see what it can do.
  6. Some basic functionality include:
  7.  
  8. 1. Compiling latex with multiple repetitions to ensure correct references,
  9. with options to clean previous output files and build a file with an
  10. integrated bibliography.
  11. 2. Consolidate all active files in a separate directory. Useful for generating
  12. a clean working directory for final upload for publication.
  13. """
  14.  
  15.  
  16. import argparse
  17. import subprocess
  18. import os
  19. import sys
  20. import re
  21. import os
  22. import shutil
  23. import glob
  24.  
  25.  
  26. def compile(args):
  27. name = args.filename.rsplit(".")[0]
  28. if not os.path.exists("%s.tex" % name):
  29. print("%s.tex does not exist!" % name)
  30. sys.exit(-1)
  31. if args.clean:
  32. torm = [name + "." + ext for ext in ["aux", "blg", "log", "bbl"]]
  33. print("Removing %s." % ", ".join(torm))
  34. try:
  35. subprocess.check_output(["rm"] + torm)
  36. except subprocess.CalledProcessError:
  37. print("No files to delete! Continuing...")
  38.  
  39. print("Running pdflatex...")
  40. output = subprocess.check_output(["pdflatex", name])
  41. if args.verbose:
  42. print(output)
  43. count = 1
  44. while ("Rerun" in output or "natbib Warning" in output) and count < 5:
  45. # This repetitive compilation process is necessary to ensure that
  46. # bibliography and references are properly updated.
  47. count += 1
  48. print("Rerunning %d" % count)
  49. print("Running bibtex...")
  50. output = subprocess.check_output(["bibtex", name])
  51. if args.verbose:
  52. print(output)
  53. print("Running pdflatex...")
  54. output = subprocess.check_output(["pdflatex", name])
  55. if args.verbose:
  56. print(output)
  57.  
  58. if args.bbl:
  59. print("Building full bbl file...")
  60. with open("%s.bbl" % name) as f:
  61. bbl = f.read()
  62.  
  63. with open("%s.tex" % name) as f:
  64. lines = []
  65. for l in f:
  66. if l.startswith("\\bibliography"):
  67. lines.append(bbl.strip())
  68. else:
  69. lines.append(l.strip())
  70.  
  71. with open("%s_bbl.tex" % name, "wt") as f:
  72. f.write("\n".join(lines))
  73.  
  74. print("%s_bbl.tex written!" % name)
  75.  
  76.  
  77.  
  78. def finalize(args):
  79. name = args.filename.rsplit(".")[0]
  80. if not os.path.exists("%s.tex" % name):
  81. print("%s.tex does not exist!" % name)
  82. sys.exit(-1)
  83.  
  84. tex = "%s.tex" % name
  85.  
  86. srcdir = os.path.dirname(os.path.abspath(tex))
  87.  
  88. with open(tex) as f:
  89. contents = f.read()
  90.  
  91. dest = args.output_dir
  92.  
  93. os.mkdir(dest)
  94.  
  95. def process_pattern(p):
  96. for m in re.finditer(p, contents, re.MULTILINE):
  97. fname = m.group(2)
  98. found = False
  99. for ext in ["", ".pdf", ".eps"]:
  100. if os.path.exists(fname + ext):
  101. fname += ext
  102. found = True
  103. break
  104. if not found:
  105. fnames = glob.glob(fname + "*")
  106. if not fnames:
  107. print("%s not found!")
  108. sys.exit(-1)
  109. else:
  110. fname = fnames[0]
  111.  
  112. print("Copying %s..." % fname)
  113. shutil.copy(os.path.join(srcdir, fname),
  114. os.path.join(dest, fname))
  115.  
  116. process_pattern("\\includegraphics(\[[^\]]+\])*\{([^\}]+)\}")
  117. process_pattern("bibliography(\[[^\]]+\])*\{([^\}]+)\}")
  118.  
  119. shutil.copy(tex, os.path.join(dest, args.filename))
  120.  
  121.  
  122. if __name__ == "__main__":
  123. parser = argparse.ArgumentParser(
  124. description="""
  125. pyltx is a convenient script that provides useful tools for LaTeX. "
  126. "Type \"pyltx -h\" for help.""",
  127. epilog="Author: Shyue Ping Ong")
  128.  
  129. subparsers = parser.add_subparsers()
  130.  
  131. parser_compile = subparsers.add_parser("compile", help="Compile a file")
  132.  
  133. parser_compile.add_argument("filename", metavar="filename", default="main",
  134. type=str, nargs="?",
  135. help="Filename to compile.")
  136. parser_compile.add_argument(
  137. "-v", "--verbose", dest="verbose",
  138. action="store_true",
  139. help="Verbose mode. Output from all commands are printed.")
  140.  
  141. parser_compile.add_argument(
  142. "-c", "--clean", dest="clean",
  143. action="store_true",
  144. help="Clean the output files before compilation. Latex usually has the"
  145. " usual aux, blg, bbl files. This will delete all those files to"
  146. " force a clean compile.")
  147. parser_compile.add_argument(
  148. "-b", "--bbl", dest="bbl",
  149. action="store_true",
  150. help="Build a file with a full bbl integrated rather than in a "
  151. "separate bibtex. Some journals require this. The integrated file"
  152. " is named <filename>__bbl.tex.")
  153. parser_compile.set_defaults(func=compile)
  154.  
  155. parser_finalize = subparsers.add_parser(
  156. "finalize",
  157. help="Consolidate all actually used files in a new directory. Useful"
  158. " for preparing final submission. Files which do not appear in"
  159. " the actual .tex file will not be included in the new dir.")
  160.  
  161. parser_finalize.add_argument(
  162. "filename", metavar="filename", default="main",
  163. type=str, nargs="?", help="Filename to compile.")
  164. parser_finalize.add_argument("-o", "--output_dir", dest="output_dir",
  165. type=str, default="final",
  166. help="Directory to output files to.")
  167. parser_finalize.set_defaults(func=finalize)
  168.  
  169. args = parser.parse_args()
  170.  
  171. try:
  172. a = getattr(args, "func")
  173. except AttributeError:
  174. parser.print_help()
  175. sys.exit(0)
  176. args.func(args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement