##// END OF EJS Templates
Merge pull request #7453 from takluyver/check-latex-commands...
Min RK -
r19925:dd150e70 merge
parent child Browse files
Show More
@@ -1,141 +1,147 b''
1 """Export to PDF via latex"""
1 """Export to PDF via latex"""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 import subprocess
6 import subprocess
7 import os
7 import os
8 import sys
8 import sys
9
9
10 from IPython.utils.process import find_cmd
10 from IPython.utils.traitlets import Integer, List, Bool, Instance
11 from IPython.utils.traitlets import Integer, List, Bool, Instance
11 from IPython.utils.tempdir import TemporaryWorkingDirectory
12 from IPython.utils.tempdir import TemporaryWorkingDirectory
12 from .latex import LatexExporter
13 from .latex import LatexExporter
13
14
14
15
15 class PDFExporter(LatexExporter):
16 class PDFExporter(LatexExporter):
16 """Writer designed to write to PDF files"""
17 """Writer designed to write to PDF files"""
17
18
18 latex_count = Integer(3, config=True,
19 latex_count = Integer(3, config=True,
19 help="How many times latex will be called."
20 help="How many times latex will be called."
20 )
21 )
21
22
22 latex_command = List([u"pdflatex", u"{filename}"], config=True,
23 latex_command = List([u"pdflatex", u"{filename}"], config=True,
23 help="Shell command used to compile latex."
24 help="Shell command used to compile latex."
24 )
25 )
25
26
26 bib_command = List([u"bibtex", u"{filename}"], config=True,
27 bib_command = List([u"bibtex", u"{filename}"], config=True,
27 help="Shell command used to run bibtex."
28 help="Shell command used to run bibtex."
28 )
29 )
29
30
30 verbose = Bool(False, config=True,
31 verbose = Bool(False, config=True,
31 help="Whether to display the output of latex commands."
32 help="Whether to display the output of latex commands."
32 )
33 )
33
34
34 temp_file_exts = List(['.aux', '.bbl', '.blg', '.idx', '.log', '.out'], config=True,
35 temp_file_exts = List(['.aux', '.bbl', '.blg', '.idx', '.log', '.out'], config=True,
35 help="File extensions of temp files to remove after running."
36 help="File extensions of temp files to remove after running."
36 )
37 )
37
38
38 writer = Instance("IPython.nbconvert.writers.FilesWriter", args=())
39 writer = Instance("IPython.nbconvert.writers.FilesWriter", args=())
39
40
40 def run_command(self, command_list, filename, count, log_function):
41 def run_command(self, command_list, filename, count, log_function):
41 """Run command_list count times.
42 """Run command_list count times.
42
43
43 Parameters
44 Parameters
44 ----------
45 ----------
45 command_list : list
46 command_list : list
46 A list of args to provide to Popen. Each element of this
47 A list of args to provide to Popen. Each element of this
47 list will be interpolated with the filename to convert.
48 list will be interpolated with the filename to convert.
48 filename : unicode
49 filename : unicode
49 The name of the file to convert.
50 The name of the file to convert.
50 count : int
51 count : int
51 How many times to run the command.
52 How many times to run the command.
52
53
53 Returns
54 Returns
54 -------
55 -------
55 success : bool
56 success : bool
56 A boolean indicating if the command was successful (True)
57 A boolean indicating if the command was successful (True)
57 or failed (False).
58 or failed (False).
58 """
59 """
59 command = [c.format(filename=filename) for c in command_list]
60 command = [c.format(filename=filename) for c in command_list]
60 #In windows and python 2.x there is a bug in subprocess.Popen and
61
62 # On windows with python 2.x there is a bug in subprocess.Popen and
61 # unicode commands are not supported
63 # unicode commands are not supported
62 if sys.platform == 'win32' and sys.version_info < (3,0):
64 if sys.platform == 'win32' and sys.version_info < (3,0):
63 #We must use cp1252 encoding for calling subprocess.Popen
65 #We must use cp1252 encoding for calling subprocess.Popen
64 #Note that sys.stdin.encoding and encoding.DEFAULT_ENCODING
66 #Note that sys.stdin.encoding and encoding.DEFAULT_ENCODING
65 # could be different (cp437 in case of dos console)
67 # could be different (cp437 in case of dos console)
66 command = [c.encode('cp1252') for c in command]
68 command = [c.encode('cp1252') for c in command]
69
70 # This will throw a clearer error if the command is not found
71 find_cmd(command_list[0])
72
67 times = 'time' if count == 1 else 'times'
73 times = 'time' if count == 1 else 'times'
68 self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)
74 self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)
69 with open(os.devnull, 'rb') as null:
75 with open(os.devnull, 'rb') as null:
70 stdout = subprocess.PIPE if not self.verbose else None
76 stdout = subprocess.PIPE if not self.verbose else None
71 for index in range(count):
77 for index in range(count):
72 p = subprocess.Popen(command, stdout=stdout, stdin=null)
78 p = subprocess.Popen(command, stdout=stdout, stdin=null)
73 out, err = p.communicate()
79 out, err = p.communicate()
74 if p.returncode:
80 if p.returncode:
75 if self.verbose:
81 if self.verbose:
76 # verbose means I didn't capture stdout with PIPE,
82 # verbose means I didn't capture stdout with PIPE,
77 # so it's already been displayed and `out` is None.
83 # so it's already been displayed and `out` is None.
78 out = u''
84 out = u''
79 else:
85 else:
80 out = out.decode('utf-8', 'replace')
86 out = out.decode('utf-8', 'replace')
81 log_function(command, out)
87 log_function(command, out)
82 return False # failure
88 return False # failure
83 return True # success
89 return True # success
84
90
85 def run_latex(self, filename):
91 def run_latex(self, filename):
86 """Run pdflatex self.latex_count times."""
92 """Run pdflatex self.latex_count times."""
87
93
88 def log_error(command, out):
94 def log_error(command, out):
89 self.log.critical(u"%s failed: %s\n%s", command[0], command, out)
95 self.log.critical(u"%s failed: %s\n%s", command[0], command, out)
90
96
91 return self.run_command(self.latex_command, filename,
97 return self.run_command(self.latex_command, filename,
92 self.latex_count, log_error)
98 self.latex_count, log_error)
93
99
94 def run_bib(self, filename):
100 def run_bib(self, filename):
95 """Run bibtex self.latex_count times."""
101 """Run bibtex self.latex_count times."""
96 filename = os.path.splitext(filename)[0]
102 filename = os.path.splitext(filename)[0]
97
103
98 def log_error(command, out):
104 def log_error(command, out):
99 self.log.warn('%s had problems, most likely because there were no citations',
105 self.log.warn('%s had problems, most likely because there were no citations',
100 command[0])
106 command[0])
101 self.log.debug(u"%s output: %s\n%s", command[0], command, out)
107 self.log.debug(u"%s output: %s\n%s", command[0], command, out)
102
108
103 return self.run_command(self.bib_command, filename, 1, log_error)
109 return self.run_command(self.bib_command, filename, 1, log_error)
104
110
105 def clean_temp_files(self, filename):
111 def clean_temp_files(self, filename):
106 """Remove temporary files created by pdflatex/bibtex."""
112 """Remove temporary files created by pdflatex/bibtex."""
107 self.log.info("Removing temporary LaTeX files")
113 self.log.info("Removing temporary LaTeX files")
108 filename = os.path.splitext(filename)[0]
114 filename = os.path.splitext(filename)[0]
109 for ext in self.temp_file_exts:
115 for ext in self.temp_file_exts:
110 try:
116 try:
111 os.remove(filename+ext)
117 os.remove(filename+ext)
112 except OSError:
118 except OSError:
113 pass
119 pass
114
120
115 def from_notebook_node(self, nb, resources=None, **kw):
121 def from_notebook_node(self, nb, resources=None, **kw):
116 latex, resources = super(PDFExporter, self).from_notebook_node(
122 latex, resources = super(PDFExporter, self).from_notebook_node(
117 nb, resources=resources, **kw
123 nb, resources=resources, **kw
118 )
124 )
119 with TemporaryWorkingDirectory() as td:
125 with TemporaryWorkingDirectory() as td:
120 notebook_name = "notebook"
126 notebook_name = "notebook"
121 tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
127 tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
122 self.log.info("Building PDF")
128 self.log.info("Building PDF")
123 rc = self.run_latex(tex_file)
129 rc = self.run_latex(tex_file)
124 if not rc:
130 if not rc:
125 rc = self.run_bib(tex_file)
131 rc = self.run_bib(tex_file)
126 if not rc:
132 if not rc:
127 rc = self.run_latex(tex_file)
133 rc = self.run_latex(tex_file)
128
134
129 pdf_file = notebook_name + '.pdf'
135 pdf_file = notebook_name + '.pdf'
130 if not os.path.isfile(pdf_file):
136 if not os.path.isfile(pdf_file):
131 raise RuntimeError("PDF creating failed")
137 raise RuntimeError("PDF creating failed")
132 self.log.info('PDF successfully created')
138 self.log.info('PDF successfully created')
133 with open(pdf_file, 'rb') as f:
139 with open(pdf_file, 'rb') as f:
134 pdf_data = f.read()
140 pdf_data = f.read()
135
141
136 # convert output extension to pdf
142 # convert output extension to pdf
137 # the writer above required it to be tex
143 # the writer above required it to be tex
138 resources['output_extension'] = '.pdf'
144 resources['output_extension'] = '.pdf'
139
145
140 return pdf_data, resources
146 return pdf_data, resources
141
147
General Comments 0
You need to be logged in to leave comments. Login now