12
12
Files that generate images should start with 'plot'
13
13
14
14
"""
15
- from __future__ import division , print_function , absolute_import
15
+ from __future__ import (division , print_function , absolute_import ,
16
+ unicode_literals )
16
17
from time import time
17
18
import ast
19
+ import codecs
18
20
import hashlib
19
21
import os
20
22
import re
@@ -49,9 +51,9 @@ def prefixed_lines():
49
51
return '' .join (prefixed_lines ())
50
52
51
53
try :
52
- from StringIO import StringIO
54
+ from BytesIO import BytesIO
53
55
except ImportError :
54
- from io import StringIO
56
+ from io import BytesIO
55
57
56
58
try :
57
59
# make sure that the Agg backend is set before importing any
@@ -87,13 +89,25 @@ def __init__(self, file1, file2):
87
89
88
90
def write (self , data ):
89
91
self .file1 .write (data )
90
- self .file2 .write (unicode ( data )) # this is the StringIO
92
+ self .file2 .write (data )
91
93
92
94
def flush (self ):
93
95
self .file1 .flush ()
94
96
self .file2 .flush ()
95
97
96
98
99
+ class MyBytesIO (BytesIO ):
100
+ """Helper to deal with unicode not having buffer interface on Py2.7"""
101
+ def write (self , data ):
102
+ # "unicode" objects don't have a buffer interface on Py2.7,
103
+ # so we need to manually convert
104
+ if isinstance (data , unicode ):
105
+ data = data .encode ('utf-8' )
106
+ super (MyBytesIO , self ).write (data )
107
+
108
+ def getvalue (self ):
109
+ return super (MyBytesIO , self ).getvalue ().decode ('utf-8' )
110
+
97
111
###############################################################################
98
112
CODE_DOWNLOAD = """**Total running time of the script:**
99
113
({0:.0f} minutes {1:.3f} seconds)\n \n
@@ -125,7 +139,7 @@ def flush(self):
125
139
"""
126
140
127
141
128
- CODE_OUTPUT = u """.. rst-class:: sphx-glr-script-out
142
+ CODE_OUTPUT = """.. rst-class:: sphx-glr-script-out
129
143
130
144
Out::
131
145
@@ -144,6 +158,9 @@ def get_docstring_and_rest(filename):
144
158
rest: str
145
159
`filename` content without the docstring
146
160
"""
161
+ # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't
162
+ # seem to work with unicode strings in Python2.7
163
+ # "SyntaxError: encoding declaration in Unicode string"
147
164
with open (filename , 'rb' ) as f :
148
165
content = f .read ()
149
166
@@ -206,8 +223,8 @@ def split_code_and_text_blocks(source_file):
206
223
207
224
def codestr2rst (codestr , lang = 'python' ):
208
225
"""Return reStructuredText code block from code string"""
209
- code_directive = u "\n .. code-block:: {0}\n \n " .format (lang )
210
- indented_block = indent (codestr , u ' ' * 4 )
226
+ code_directive = "\n .. code-block:: {0}\n \n " .format (lang )
227
+ indented_block = indent (codestr , ' ' * 4 )
211
228
return code_directive + indented_block
212
229
213
230
@@ -464,7 +481,7 @@ def execute_script(code_block, example_globals, image_path, fig_count,
464
481
# First cd in the original example dir, so that any file
465
482
# created by the example get created in this directory
466
483
os .chdir (os .path .dirname (src_file ))
467
- my_buffer = StringIO ()
484
+ my_buffer = MyBytesIO ()
468
485
my_stdout = Tee (sys .stdout , my_buffer )
469
486
sys .stdout = my_stdout
470
487
@@ -476,7 +493,7 @@ def execute_script(code_block, example_globals, image_path, fig_count,
476
493
477
494
my_stdout = my_buffer .getvalue ().strip ().expandtabs ()
478
495
if my_stdout :
479
- stdout = CODE_OUTPUT .format (indent (my_stdout , u ' ' * 4 ))
496
+ stdout = CODE_OUTPUT .format (indent (my_stdout , ' ' * 4 ))
480
497
os .chdir (cwd )
481
498
figure_list = save_figures (image_path , fig_count , gallery_conf )
482
499
@@ -518,7 +535,7 @@ def execute_script(code_block, example_globals, image_path, fig_count,
518
535
os .chdir (cwd )
519
536
520
537
print (" - time elapsed : %.2g sec" % time_elapsed )
521
- code_output = u "\n {0}\n \n {1}\n \n " .format (image_list , stdout )
538
+ code_output = "\n {0}\n \n {1}\n \n " .format (image_list , stdout )
522
539
523
540
return code_output , time_elapsed , fig_count + len (figure_list )
524
541
@@ -554,7 +571,7 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
554
571
time_elapsed = 0
555
572
556
573
ref_fname = example_file .replace (os .path .sep , '_' )
557
- example_rst = u """\n \n .. _sphx_glr_{0}:\n \n """ .format (ref_fname )
574
+ example_rst = """\n \n .. _sphx_glr_{0}:\n \n """ .format (ref_fname )
558
575
example_nb = Notebook (fname , target_dir )
559
576
560
577
filename_pattern = gallery_conf .get ('filename_pattern' )
@@ -613,9 +630,10 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
613
630
614
631
time_m , time_s = divmod (time_elapsed , 60 )
615
632
example_nb .save_file ()
616
- with open (os .path .join (target_dir , base_image_name + '.rst' ), 'wb' ) as f :
633
+ with codecs .open (os .path .join (target_dir , base_image_name + '.rst' ),
634
+ 'w' , 'utf-8' ) as f :
617
635
example_rst += CODE_DOWNLOAD .format (time_m , time_s , fname ,
618
636
example_nb .file_name )
619
- f .write (example_rst . encode ( 'utf-8' ) )
637
+ f .write (example_rst )
620
638
621
639
return amount_of_code , time_elapsed
0 commit comments