1commit fc59dd90f03cf88f4cf16c07204809f2239284ee
2Author: Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>
3Date: Thu Dec 20 00:02:53 2012 +0100
4
5 Add support for python3
6
7 Libreoffice 4.0 will switch its internal python version to 3.3.0
8 so it's to support that.
9
10 Porting done automatically 2to3 plus print_function import added
11 manually. Tested on both libreoffice master with internal python
12 and with libreoffince 3.6.4 on debian with system python 2.7.
13
14 This bumps the minimal python version to 2.6 since 2.5 does not
15 have the print function.
16
17diff --git a/unoconv b/unoconv
18index 30e6706..f72cf08 100755
19--- a/unoconv
20+++ b/unoconv
21@@ -14,6 +14,8 @@
22 ### Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 ### Copyright 2007-2010 Dag Wieers <dag@wieers.com>
24
25+from __future__ import print_function
26+
27 from distutils.version import LooseVersion
28 import getopt
29 import glob
30@@ -77,11 +79,11 @@ def find_offices():
31 else:
32
33 if os.name in ( 'nt', 'os2' ):
34- if 'PROGRAMFILES' in os.environ.keys():
35+ if 'PROGRAMFILES' in list(os.environ.keys()):
36 extrapaths += glob.glob(os.environ['PROGRAMFILES']+'\\LibreOffice*') + \
37 glob.glob(os.environ['PROGRAMFILES']+'\\OpenOffice.org*')
38
39- if 'PROGRAMFILES(X86)' in os.environ.keys():
40+ if 'PROGRAMFILES(X86)' in list(os.environ.keys()):
41 extrapaths += glob.glob(os.environ['PROGRAMFILES(X86)']+'\\LibreOffice*') + \
42 glob.glob(os.environ['PROGRAMFILES(X86)']+'\\OpenOffice.org*')
43
44@@ -233,18 +235,18 @@ def office_environ(office):
45
46 def debug_office():
47 if 'URE_BOOTSTRAP' in os.environ:
48- print >>sys.stderr, 'URE_BOOTSTRAP=%s' % os.environ['URE_BOOTSTRAP']
49+ print('URE_BOOTSTRAP=%s' % os.environ['URE_BOOTSTRAP'], file=sys.stderr)
50 if 'UNO_PATH' in os.environ:
51- print >>sys.stderr, 'UNO_PATH=%s' % os.environ['UNO_PATH']
52+ print('UNO_PATH=%s' % os.environ['UNO_PATH'], file=sys.stderr)
53 if 'UNO_TYPES' in os.environ:
54- print >>sys.stderr, 'UNO_TYPES=%s' % os.environ['UNO_TYPES']
55- print 'PATH=%s' % os.environ['PATH']
56+ print('UNO_TYPES=%s' % os.environ['UNO_TYPES'], file=sys.stderr)
57+ print('PATH=%s' % os.environ['PATH'])
58 if 'PYTHONHOME' in os.environ:
59- print >>sys.stderr, 'PYTHONHOME=%s' % os.environ['PYTHONHOME']
60+ print('PYTHONHOME=%s' % os.environ['PYTHONHOME'], file=sys.stderr)
61 if 'PYTHONPATH' in os.environ:
62- print >>sys.stderr, 'PYTHONPATH=%s' % os.environ['PYTHONPATH']
63+ print('PYTHONPATH=%s' % os.environ['PYTHONPATH'], file=sys.stderr)
64 if 'LD_LIBRARY_PATH' in os.environ:
65- print >>sys.stderr, 'LD_LIBRARY_PATH=%s' % os.environ['LD_LIBRARY_PATH']
66+ print('LD_LIBRARY_PATH=%s' % os.environ['LD_LIBRARY_PATH'], file=sys.stderr)
67
68 def python_switch(office):
69 if office.pythonhome:
70@@ -335,11 +337,11 @@ class FmtList:
71 return ret
72
73 def display(self, doctype):
74- print >>sys.stderr, "The following list of %s formats are currently available:\n" % doctype
75+ print("The following list of %s formats are currently available:\n" % doctype, file=sys.stderr)
76 for fmt in self.list:
77 if fmt.doctype == doctype:
78- print >>sys.stderr, " %-8s - %s" % (fmt.name, fmt)
79- print >>sys.stderr
80+ print(" %-8s - %s" % (fmt.name, fmt), file=sys.stderr)
81+ print(file=sys.stderr)
82
83 fmts = FmtList()
84
85@@ -530,14 +532,14 @@ class Options:
86 'outputpath', 'password=', 'pipe=', 'port=', 'server=',
87 'timeout=', 'show', 'stdout', 'template', 'verbose',
88 'version'] )
89- except getopt.error, exc:
90- print 'unoconv: %s, try unoconv -h for a list of all the options' % str(exc)
91+ except getopt.error as exc:
92+ print('unoconv: %s, try unoconv -h for a list of all the options' % str(exc))
93 sys.exit(255)
94
95 for opt, arg in opts:
96 if opt in ['-h', '--help']:
97 self.usage()
98- print
99+ print()
100 self.help()
101 sys.exit(1)
102 elif opt in ['-c', '--connection']:
103@@ -562,7 +564,7 @@ class Options:
104 except ValueError:
105 self.exportfilter.append( PropertyValue( name, 0, value, 0 ) )
106 else:
107- print >>sys.stderr, 'Warning: Option %s cannot be parsed, ignoring.' % arg
108+ print('Warning: Option %s cannot be parsed, ignoring.' % arg, file=sys.stderr)
109 elif opt in ['-f', '--format']:
110 self.format = arg
111 elif opt in ['-i', '--import']:
112@@ -581,7 +583,7 @@ class Options:
113 except ValueError:
114 self.importfilter.append( PropertyValue( name, 0, value, 0 ) )
115 else:
116- print >>sys.stderr, 'Warning: Option %s cannot be parsed, ignoring.' % arg
117+ print('Warning: Option %s cannot be parsed, ignoring.' % arg, file=sys.stderr)
118 elif opt in ['-l', '--listener']:
119 self.listener = True
120 elif opt in ['-n', '--no-launch']:
121@@ -589,7 +591,7 @@ class Options:
122 elif opt in ['-o', '--output']:
123 self.output = arg
124 elif opt in ['--outputpath']:
125- print >>sys.stderr, 'Warning: This option is deprecated by --output.'
126+ print('Warning: This option is deprecated by --output.', file=sys.stderr)
127 self.output = arg
128 elif opt in ['--password']:
129 self.password = arg
130@@ -615,13 +617,13 @@ class Options:
131
132 ### Enable verbosity
133 if self.verbose >= 2:
134- print >>sys.stderr, 'Verbosity set to level %d' % self.verbose
135+ print('Verbosity set to level %d' % self.verbose, file=sys.stderr)
136
137 self.filenames = args
138
139 if not self.listener and not self.showlist and self.doctype != 'list' and not self.filenames:
140- print >>sys.stderr, 'unoconv: you have to provide a filename as argument'
141- print >>sys.stderr, 'Try `unoconv -h\' for more information.'
142+ print('unoconv: you have to provide a filename as argument', file=sys.stderr)
143+ print('Try `unoconv -h\' for more information.', file=sys.stderr)
144 sys.exit(255)
145
146 ### Set connection string
147@@ -659,21 +661,21 @@ class Options:
148 ### Get office product information
149 product = uno.getComponentContext().ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider").createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", UnoProps(nodepath="/org.openoffice.Setup/Product"))
150
151- print 'unoconv %s' % VERSION
152- print 'Written by Dag Wieers <dag@wieers.com>'
153- print 'Homepage at http://dag.wieers.com/home-made/unoconv/'
154- print
155- print 'platform %s/%s' % (os.name, sys.platform)
156- print 'python %s' % sys.version
157- print product.ooName, product.ooSetupVersion
158+ print('unoconv %s' % VERSION)
159+ print('Written by Dag Wieers <dag@wieers.com>')
160+ print('Homepage at http://dag.wieers.com/home-made/unoconv/')
161+ print()
162+ print('platform %s/%s' % (os.name, sys.platform))
163+ print('python %s' % sys.version)
164+ print(product.ooName, product.ooSetupVersion)
165 # print
166 # print 'build revision $Rev$'
167
168 def usage(self):
169- print >>sys.stderr, 'usage: unoconv [options] file [file2 ..]'
170+ print('usage: unoconv [options] file [file2 ..]', file=sys.stderr)
171
172 def help(self):
173- print >>sys.stderr, '''Convert from and to any format supported by LibreOffice
174+ print('''Convert from and to any format supported by LibreOffice
175
176 unoconv options:
177 -c, --connection=string use a custom connection string
178@@ -698,7 +700,7 @@ unoconv options:
179 -t, --template=file import the styles from template (.ott)
180 -T, --timeout=secs timeout after secs if connection to listener fails
181 -v, --verbose be more and more verbose (-vvv for debugging)
182-'''
183+''', file=sys.stderr)
184
185 class Convertor:
186 def __init__(self):
187@@ -714,7 +716,7 @@ class Convertor:
188 info(3, 'Connection type: %s' % op.connection)
189 try:
190 unocontext = resolver.resolve("uno:%s" % op.connection)
191- except NoConnectException, e:
192+ except NoConnectException as e:
193 # info(3, "Existing listener not found.\n%s" % e)
194 info(3, "Existing listener not found.")
195
196@@ -749,7 +751,7 @@ class Convertor:
197 raise
198 else:
199 error("Failed to connect to %s (pid=%s) in %d seconds.\n%s" % (office.binary, ooproc.pid, op.timeout, e))
200- except Exception, e:
201+ except Exception as e:
202 raise
203 error("Launch of %s failed.\n%s" % (office.binary, e))
204
205@@ -799,9 +801,9 @@ class Convertor:
206 ### No format found, throw error
207 if not outputfmt:
208 if doctype:
209- print >>sys.stderr, 'unoconv: format [%s/%s] is not known to unoconv.' % (op.doctype, op.format)
210+ print('unoconv: format [%s/%s] is not known to unoconv.' % (op.doctype, op.format), file=sys.stderr)
211 else:
212- print >>sys.stderr, 'unoconv: format [%s] is not known to unoconv.' % op.format
213+ print('unoconv: format [%s] is not known to unoconv.' % op.format, file=sys.stderr)
214 die(1)
215
216 return outputfmt
217@@ -813,10 +815,10 @@ class Convertor:
218 outputfmt = self.getformat(inputfn)
219
220 if op.verbose > 0:
221- print >>sys.stderr, 'Input file:', inputfn
222+ print('Input file:', inputfn, file=sys.stderr)
223
224 if not os.path.exists(inputfn):
225- print >>sys.stderr, 'unoconv: file `%s\' does not exist.' % inputfn
226+ print('unoconv: file `%s\' does not exist.' % inputfn, file=sys.stderr)
227 exitcode = 1
228
229 try:
230@@ -854,7 +856,7 @@ class Convertor:
231 templateurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(op.template))
232 document.StyleFamilies.loadStylesFromURL(templateurl, templateprops)
233 else:
234- print >>sys.stderr, 'unoconv: template file `%s\' does not exist.' % op.template
235+ print('unoconv: template file `%s\' does not exist.' % op.template, file=sys.stderr)
236 exitcode = 1
237
238 ### Update document links
239@@ -924,40 +926,40 @@ class Convertor:
240
241 try:
242 document.storeToURL(outputurl, tuple(outputprops) )
243- except IOException, e:
244+ except IOException as e:
245 raise UnoException("Unable to store document to %s (ErrCode %d)\n\nProperties: %s" % (outputurl, e.ErrCode, outputprops), None)
246
247 phase = "dispose"
248 document.dispose()
249 document.close(True)
250
251- except SystemError, e:
252+ except SystemError as e:
253 error("unoconv: SystemError during %s phase:\n%s" % (phase, e))
254 exitcode = 1
255
256- except RuntimeException, e:
257+ except RuntimeException as e:
258 error("unoconv: RuntimeException during %s phase:\nOffice probably died. %s" % (phase, e))
259 exitcode = 6
260
261- except DisposedException, e:
262+ except DisposedException as e:
263 error("unoconv: DisposedException during %s phase:\nOffice probably died. %s" % (phase, e))
264 exitcode = 7
265
266- except IllegalArgumentException, e:
267+ except IllegalArgumentException as e:
268 error("UNO IllegalArgument during %s phase:\nSource file cannot be read. %s" % (phase, e))
269 exitcode = 8
270
271- except IOException, e:
272+ except IOException as e:
273 # for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
274 error("unoconv: IOException during %s phase:\n%s" % (phase, e.Message))
275 exitcode = 3
276
277- except CannotConvertException, e:
278+ except CannotConvertException as e:
279 # for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
280 error("unoconv: CannotConvertException during %s phase:\n%s" % (phase, e.Message))
281 exitcode = 4
282
283- except UnoException, e:
284+ except UnoException as e:
285 if hasattr(e, 'ErrCode'):
286 error("unoconv: UnoException during %s phase in %s (ErrCode %d)" % (phase, repr(e.__class__), e.ErrCode))
287 exitcode = e.ErrCode
288@@ -982,7 +984,7 @@ class Listener:
289 product = self.svcmgr.createInstance("com.sun.star.configuration.ConfigurationProvider").createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", UnoProps(nodepath="/org.openoffice.Setup/Product"))
290 try:
291 unocontext = resolver.resolve("uno:%s" % op.connection)
292- except NoConnectException, e:
293+ except NoConnectException as e:
294 pass
295 else:
296 info(1, "Existing %s listener found, nothing to do." % product.ooName)
297@@ -991,25 +993,25 @@ class Listener:
298 subprocess.call([office.binary, "-headless", "-invisible", "-nocrashreport", "-nodefault", "-nologo", "-nofirststartwizard", "-norestore", "-accept=%s" % op.connection], env=os.environ)
299 else:
300 subprocess.call([office.binary, "--headless", "--invisible", "--nocrashreport", "--nodefault", "--nologo", "--nofirststartwizard", "--norestore", "--accept=%s" % op.connection], env=os.environ)
301- except Exception, e:
302+ except Exception as e:
303 error("Launch of %s failed.\n%s" % (office.binary, e))
304 else:
305 info(1, "Existing %s listener found, nothing to do." % product.ooName)
306
307 def error(msg):
308 "Output error message"
309- print >>sys.stderr, msg
310+ print(msg, file=sys.stderr)
311
312 def info(level, msg):
313 "Output info message"
314 if 'op' not in globals():
315 pass
316 elif op.verbose >= 3 and level >= 3:
317- print >>sys.stderr, "DEBUG:", msg
318+ print("DEBUG:", msg, file=sys.stderr)
319 elif not op.stdout and level <= op.verbose:
320- print >>sys.stdout, msg
321+ print(msg, file=sys.stdout)
322 elif level <= op.verbose:
323- print >>sys.stderr, msg
324+ print(msg, file=sys.stderr)
325
326 def die(ret, msg=None):
327 "Print optional error and exit with errorcode"
328@@ -1031,7 +1033,7 @@ def die(ret, msg=None):
329 subprocess.Popen([office.binary, "--headless", "--invisible", "--nocrashreport", "--nodefault", "--nofirststartwizard", "--nologo", "--norestore", "--unaccept=%s" % op.connection], env=os.environ)
330 ooproc.wait()
331 info(2, '%s listener successfully disabled.' % product.ooName)
332- except Exception, e:
333+ except Exception as e:
334 error("Terminate using %s failed.\n%s" % (office.binary, e))
335
336 ### If there is no GUI attached to the instance, terminate instance
337@@ -1080,7 +1082,7 @@ def main():
338 for inputfn in op.filenames:
339 convertor.convert(inputfn)
340
341- except NoConnectException, e:
342+ except NoConnectException as e:
343 error("unoconv: could not find an existing connection to LibreOffice at %s:%s." % (op.server, op.port))
344 if op.connection:
345 info(0, "Please start an LibreOffice instance on server '%s' by doing:\n\n unoconv --listener --server %s --port %s\n\nor alternatively:\n\n soffice -nologo -nodefault -accept=\"%s\"" % (op.server, op.server, op.port, op.connection))
346@@ -1110,14 +1112,14 @@ if __name__ == '__main__':
347 break
348 except:
349 # debug_office()
350- print >>sys.stderr, "unoconv: Cannot find a suitable pyuno library and python binary combination in %s" % of
351- print >>sys.stderr, "ERROR:", sys.exc_info()[1]
352- print >>sys.stderr
353+ print("unoconv: Cannot find a suitable pyuno library and python binary combination in %s" % of, file=sys.stderr)
354+ print("ERROR:", sys.exc_info()[1], file=sys.stderr)
355+ print(file=sys.stderr)
356 else:
357 # debug_office()
358- print >>sys.stderr, "unoconv: Cannot find a suitable office installation on your system."
359- print >>sys.stderr, "ERROR: Please locate your office installation and send your feedback to:"
360- print >>sys.stderr, " http://github.com/dagwieers/unoconv/issues"
361+ print("unoconv: Cannot find a suitable office installation on your system.", file=sys.stderr)
362+ print("ERROR: Please locate your office installation and send your feedback to:", file=sys.stderr)
363+ print(" http://github.com/dagwieers/unoconv/issues", file=sys.stderr)
364 sys.exit(1)
365
366 ### Now that we have found a working pyuno library, let's import some classes
367@@ -1160,6 +1162,6 @@ if __name__ == '__main__':
368
369 try:
370 main()
371- except KeyboardInterrupt, e:
372+ except KeyboardInterrupt as e:
373 die(6, 'Exiting on user request')
374 die(exitcode)