Update Python scripts to Python 3+

Remove support for Python 2

Use formatted strings where appropriated
This commit is contained in:
José Matos 2024-06-10 11:29:56 +01:00
parent f9ec4186d7
commit 04ecabef60
27 changed files with 67 additions and 161 deletions

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file TeXFiles.py # file TeXFiles.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -35,7 +33,6 @@
# relies on python and kpsewhich (no shell command is used). # relies on python and kpsewhich (no shell command is used).
# #
from __future__ import print_function
import os, sys, re import os, sys, re
cls_stylefile = 'clsFiles.lst' cls_stylefile = 'clsFiles.lst'

View File

@ -94,7 +94,7 @@ def main(argv):
if dv2dt_status != None or len(dv2dt_data) == 0: if dv2dt_status != None or len(dv2dt_data) == 0:
dv2dt_err = dv2dt_stderr.read() dv2dt_err = dv2dt_stderr.read()
error("Failed: %s\n%s\n" % ( dv2dt_call, dv2dt_err) ) error(f"Failed: {dv2dt_call}\n{dv2dt_err}\n" )
# Manipulate the .dtl file. # Manipulate the .dtl file.
dtl_data = manipulated_dtl(dv2dt_data) dtl_data = manipulated_dtl(dv2dt_data)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file convertDefault.py # file convertDefault.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -16,7 +14,6 @@
# replacement in ~/.lyx/scripts # replacement in ~/.lyx/scripts
# converts an image $2 (format $1) to $4 (format $3) # converts an image $2 (format $1) to $4 (format $3)
from __future__ import print_function
import os, re, sys import os, re, sys
# We may need some extra options only supported by recent convert versions # We may need some extra options only supported by recent convert versions
@ -73,11 +70,11 @@ if sys.argv[3] == 'ppm' and (im and version >= (6,3,5) or gm):
topts = '-flatten' topts = '-flatten'
# print (command, sys.argv[2], sys.argv[4], file= sys.stdout) # print (command, sys.argv[2], sys.argv[4], file= sys.stdout)
if (im or gm) and os.system(r'%s %s "%s" %s "%s"' % (command, sopts, sys.argv[2], topts, sys.argv[3] + ':' + sys.argv[4])) != 0: if (im or gm) and os.system(r'{} {} "{}" {} "{}"'.format(command, sopts, sys.argv[2], topts, sys.argv[3] + ':' + sys.argv[4])) != 0:
print(sys.argv[0], 'ERROR', file= sys.stderr) print(sys.argv[0], 'ERROR', file= sys.stderr)
print('Execution of "%s" failed.' % command, file= sys.stderr) print('Execution of "%s" failed.' % command, file= sys.stderr)
sys.exit(1) sys.exit(1)
elif not im and not gm and sys.platform == 'darwin' and os.system(r'%s "%s" "%s"' % (command, sys.argv[2], sys.argv[4])) != 0: elif not im and not gm and sys.platform == 'darwin' and os.system(fr'{command} "{sys.argv[2]}" "{sys.argv[4]}"') != 0:
print(sys.argv[0], 'ERROR', file= sys.stderr) print(sys.argv[0], 'ERROR', file= sys.stderr)
print('Execution of "%s" failed.' % command, file=sys.stderr) print('Execution of "%s" failed.' % command, file=sys.stderr)
sys.exit(1) sys.exit(1)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file convert_pdf.py # file convert_pdf.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file csv2lyx.py # file csv2lyx.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file docbook2epub.py # file docbook2epub.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -11,7 +9,6 @@
# Usage: # Usage:
# python docbook2epub.py java_binary saxon_path xsltproc_path xslt_path in.docbook in.orig.path out.epub # python docbook2epub.py java_binary saxon_path xsltproc_path xslt_path in.docbook in.orig.path out.epub
from __future__ import print_function
import glob import glob
import os import os
@ -19,7 +16,6 @@ import shutil
import sys import sys
import tempfile import tempfile
import zipfile import zipfile
from io import open # Required for Python 2.
def _parse_nullable_argument(arg): def _parse_nullable_argument(arg):
@ -39,7 +35,7 @@ class DocBookToEpub:
args = sys.argv args = sys.argv
if len(args) != 8: if len(args) != 8:
print('Exactly eight arguments are expected, only %s found: %s.' % (len(args), args)) print(f'Exactly eight arguments are expected, only {len(args)} found: {args}.')
sys.exit(1) sys.exit(1)
self.own_path = sys.argv[0] self.own_path = sys.argv[0]
@ -127,7 +123,7 @@ class DocBookToEpub:
# The XHTML files are also <item> tags: # The XHTML files are also <item> tags:
# <item id="id-d0e2" href="index.xhtml" media-type="application/xhtml+xml"/> # <item id="id-d0e2" href="index.xhtml" media-type="application/xhtml+xml"/>
try: try:
with open(self.package_opf, 'r') as f: with open(self.package_opf) as f:
for line in f.readlines(): for line in f.readlines():
if '<item' in line and 'media-type="image' in line: if '<item' in line and 'media-type="image' in line:
images.append(line.split('href="')[1].split('"')[0]) images.append(line.split('href="')[1].split('"')[0])
@ -154,7 +150,7 @@ class DocBookToEpub:
def change_image_paths(self, file): def change_image_paths(self, file):
# This could be optimised, as the same operation is performed a zillion times on many files: # This could be optimised, as the same operation is performed a zillion times on many files:
# https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
with open(file, 'r', encoding='utf8') as f: with open(file, encoding='utf8') as f:
contents = list(f) contents = list(f)
with open(file, 'w', encoding='utf8') as f: with open(file, 'w', encoding='utf8') as f:

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file docbook_copy.py # file docbook_copy.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -55,7 +53,7 @@ class DocBookCopier:
def in_file_needs_lilypond(self): def in_file_needs_lilypond(self):
# Really tailored to the kind of output lilypond.module makes (in lib/layouts). # Really tailored to the kind of output lilypond.module makes (in lib/layouts).
with open(self.in_file, 'r') as f: with open(self.in_file) as f:
return "language='lilypond'" in f.read() return "language='lilypond'" in f.read()
def preprocess_input_for_lilypond(self): def preprocess_input_for_lilypond(self):
@ -77,7 +75,7 @@ class DocBookCopier:
# This issue must be fixed by LilyPond, as any change in this part would make the XML # This issue must be fixed by LilyPond, as any change in this part would make the XML
# file invalid. # file invalid.
# Bug report: https://gitlab.com/lilypond/lilypond/-/issues/6204 # Bug report: https://gitlab.com/lilypond/lilypond/-/issues/6204
with open(self.in_file, 'r', encoding='utf-8') as f, open(self.in_lily_file, 'w', encoding='utf-8') as f_lily: with open(self.in_file, encoding='utf-8') as f, open(self.in_lily_file, 'w', encoding='utf-8') as f_lily:
for line in f: for line in f:
if "language='lilypond'" in line: if "language='lilypond'" in line:
line = re.sub( line = re.sub(
@ -179,7 +177,7 @@ class DocBookCopier:
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) != 4: if len(sys.argv) != 4:
print('Exactly four arguments are expected, only %s found: %s.' % (len(sys.argv), sys.argv)) print(f'Exactly four arguments are expected, only {len(sys.argv)} found: {sys.argv}.')
sys.exit(1) sys.exit(1)
DocBookCopier(sys.argv).copy() DocBookCopier(sys.argv).copy()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file ext_copy.py # file ext_copy.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -53,7 +51,7 @@ def main(argv):
error(usage(progname)) error(usage(progname))
abs_from_file = args[0] abs_from_file = args[0]
if not os.path.isabs(abs_from_file): if not os.path.isabs(abs_from_file):
error("%s is not an absolute file name.\n%s" % (abs_from_file, usage(progname))) error(f"{abs_from_file} is not an absolute file name.\n{usage(progname)}")
from_dir = os.path.dirname(abs_from_file) from_dir = os.path.dirname(abs_from_file)
# output directory # output directory
@ -64,7 +62,7 @@ def main(argv):
if targext != '.': if targext != '.':
to_dir += "." + targext to_dir += "." + targext
if not os.path.isabs(to_dir): if not os.path.isabs(to_dir):
error("%s is not an absolute file name.\n%s" % (to_dir, usage(progname))) error(f"{to_dir} is not an absolute file name.\n{usage(progname)}")
if not copy_all(from_dir, to_dir, exts): if not copy_all(from_dir, to_dir, exts):
# some kind of failure # some kind of failure

View File

@ -9,12 +9,11 @@
# This script will convert a chess position in the FEN # This script will convert a chess position in the FEN
# format to an ascii representation of the position. # format to an ascii representation of the position.
from __future__ import print_function
import sys,string,os import sys,string,os
os.close(0) os.close(0)
os.close(1) os.close(1)
sys.stdin = open(sys.argv[1],"r") sys.stdin = open(sys.argv[1])
sys.stdout = open(sys.argv[2],"w") sys.stdout = open(sys.argv[2],"w")
line = sys.stdin.readline() line = sys.stdin.readline()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file fig2pdf.py # file fig2pdf.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -26,7 +24,6 @@
# the real pdf file will be overwritten by a tex file named file.pdf. # the real pdf file will be overwritten by a tex file named file.pdf.
# #
from __future__ import print_function
import os, sys, re import os, sys, re
@ -64,13 +61,13 @@ if 'pdftex_t' in help_msg:
# Modern versions of xfig can output the image without "special" text as # Modern versions of xfig can output the image without "special" text as
# a PDF file ${base}.pdf and place the text in a LaTeX file # a PDF file ${base}.pdf and place the text in a LaTeX file
# ${base}.pdftex_t for typesetting by pdflatex itself. # ${base}.pdftex_t for typesetting by pdflatex itself.
runCommand('fig2dev -Lpdftex -p1 %s %s.pdf' % (input, outbase)) runCommand(f'fig2dev -Lpdftex -p1 {input} {outbase}.pdf')
runCommand('fig2dev -Lpdftex_t -p%s %s %s' % (outbase, input, output)) runCommand(f'fig2dev -Lpdftex_t -p{outbase} {input} {output}')
else: else:
# Older versions of xfig cannot do this, so we emulate the behaviour using # Older versions of xfig cannot do this, so we emulate the behaviour using
# pstex and pstex_t output. # pstex and pstex_t output.
runCommand('fig2dev -Lpstex %s %s.pstex' % (input, outbase)) runCommand(f'fig2dev -Lpstex {input} {outbase}.pstex')
runCommand('fig2dev -Lpstex_t -p %s %s %s' % (outbase, input, output)) runCommand(f'fig2dev -Lpstex_t -p {outbase} {input} {output}')
# manipulates the Bounding Box info to enable gs to produce # manipulates the Bounding Box info to enable gs to produce
# the appropriate PDF file from an EPS one. # the appropriate PDF file from an EPS one.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file fig2pstex.py # file fig2pstex.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -26,7 +24,6 @@
# the real eps file will be overwritten by a tex file named file.eps. # the real eps file will be overwritten by a tex file named file.eps.
# #
from __future__ import print_function
import os, sys import os, sys
# We expect two args, the names of the input and output files. # We expect two args, the names of the input and output files.
@ -44,7 +41,7 @@ outbase = os.path.splitext(output)[0]
# Generate the EPS file # Generate the EPS file
# Generate the PSTEX_T file # Generate the PSTEX_T file
if os.system('fig2dev -Lpstex %s %s.eps' % (input, outbase)) != 0 or \ if os.system(f'fig2dev -Lpstex {input} {outbase}.eps') != 0 or \
os.system('fig2dev -Lpstex_t -p%s %s %s' % (outbase, input, output)) != 0: os.system(f'fig2dev -Lpstex_t -p{outbase} {input} {output}') != 0:
print ('fig2dev fails') print ('fig2dev fails')
sys.exit(1) sys.exit(1)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file fig_copy.py # file fig_copy.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -17,7 +15,6 @@
# picture files that are stored as relative paths are replaced # picture files that are stored as relative paths are replaced
# with the absolute path. # with the absolute path.
from __future__ import print_function
import os, sys import os, sys
if len(sys.argv) != 3: if len(sys.argv) != 3:

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file html2latexwrapper.py # file html2latexwrapper.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -27,7 +25,7 @@ def usage(prog_name):
def get_encoding(from_file_name): def get_encoding(from_file_name):
'''Read the encoding from a HTML or XHTML file''' '''Read the encoding from a HTML or XHTML file'''
try: try:
from_file = open(from_file_name, 'rt') from_file = open(from_file_name)
regexpxml = re.compile(r'^\s?<\?xml\s+.*?encoding\s*=\s*"([^"]+)"', re.IGNORECASE) regexpxml = re.compile(r'^\s?<\?xml\s+.*?encoding\s*=\s*"([^"]+)"', re.IGNORECASE)
regexptype = re.compile(r'^\s?<meta\s+.*?charset\s*=\s*"([^"]+)"', re.IGNORECASE) regexptype = re.compile(r'^\s?<meta\s+.*?charset\s*=\s*"([^"]+)"', re.IGNORECASE)
for line in from_file.readlines(): for line in from_file.readlines():
@ -53,7 +51,7 @@ def main(argv):
to_file_name = argv[3] to_file_name = argv[3]
# Run gnuhtml2latex # Run gnuhtml2latex
cmd = '%s -s %s' % (converter, from_file_name) cmd = f'{converter} -s {from_file_name}'
(ret, output) = run_command(cmd, False) (ret, output) = run_command(cmd, False)
# Determine encoding of HTML file # Determine encoding of HTML file
@ -112,7 +110,7 @@ def main(argv):
break break
# Write output file and insert inputenc call if needed # Write output file and insert inputenc call if needed
to_file = open(to_file_name, 'wt') to_file = open(to_file_name, 'w')
for line in lines: for line in lines:
to_file.write(line + '\n') to_file.write(line + '\n')
if add_inputenc and line.find('\\documentclass') == 0: if add_inputenc and line.find('\\documentclass') == 0:

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file include_bib.py # file include_bib.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -27,7 +25,6 @@
# #
# Please report any problems on the devel list. # Please report any problems on the devel list.
from __future__ import print_function
import sys, os import sys, os
class secbib: class secbib:
@ -46,7 +43,7 @@ class BibError(Exception):
def InsertBib(fil, out): def InsertBib(fil, out):
''' Inserts the contents of the .bbl file instead of the bibliography in a new .tex file ''' ''' Inserts the contents of the .bbl file instead of the bibliography in a new .tex file '''
texlist = open(fil, 'r').readlines() texlist = open(fil).readlines()
# multiple bibliographies # multiple bibliographies
biblist = [] biblist = []
@ -68,7 +65,7 @@ def InsertBib(fil, out):
bibpos = biblist[0] bibpos = biblist[0]
newlist = texlist[0:bibpos] newlist = texlist[0:bibpos]
bblfile = fil[:-4] + ".bbl" bblfile = fil[:-4] + ".bbl"
bbllist = open(bblfile, 'r').readlines() bbllist = open(bblfile).readlines()
newlist += bbllist newlist += bbllist
newlist += texlist[bibpos + 1:] newlist += texlist[bibpos + 1:]

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file layout2layout.py # file layout2layout.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -365,19 +363,6 @@ currentFormat = 105
import os, re, sys import os, re, sys
import argparse import argparse
# Provide support for both python 2 and 3
# (copied from lyx2lyx)
PY2 = sys.version_info[0] == 2
if PY2:
# argparse returns strings in the commandline encoding, we need to convert.
# sys.getdefaultencoding() would not always be correct, see
# http://legacy.python.org/dev/peps/pep-0383/
def cmd_arg(arg):
return arg.decode(sys.getfilesystemencoding())
else:
cmd_arg = str
# End of code to support for both python 2 and 3
def error(message): def error(message):
sys.stderr.write(message + '\n') sys.stderr.write(message + '\n')
@ -570,15 +555,15 @@ def convert(lines, end_format):
match = re_Format.match(lines[i]) match = re_Format.match(lines[i])
if match: if match:
formatline = i formatline = i
format = int(match.group(4)) format_ = int(match.group(4))
if 1 < format < end_format: if 1 < format_ < end_format:
lines[i] = b"Format %d" % (format + 1) lines[i] = b"Format %d" % (format_ + 1)
only_comment = 0 only_comment = 0
elif format == end_format: elif format_ == end_format:
# nothing to do # nothing to do
return format return format_
else: else:
error('Cannot convert file format %s to %s' % (format, end_format)) error(f'Cannot convert file format {format_} to {end_format}')
else: else:
lines.insert(i, b"Format 2") lines.insert(i, b"Format 2")
only_comment = 0 only_comment = 0
@ -1404,9 +1389,9 @@ def main(argv):
parser.add_argument("-t", "--to", type=int, dest="format", default= currentFormat, parser.add_argument("-t", "--to", type=int, dest="format", default= currentFormat,
help=("destination layout format, default %i (latest)") % currentFormat) help=("destination layout format, default %i (latest)") % currentFormat)
parser.add_argument("input_file", nargs='?', type=cmd_arg, default=None, parser.add_argument("input_file", nargs='?', type=str, default=None,
help="input file (default stdin)") help="input file (default stdin)")
parser.add_argument("output_file", nargs='?', type=cmd_arg, default=None, parser.add_argument("output_file", nargs='?', type=str, default=None,
help="output file (default stdout)") help="output file (default stdout)")
options = parser.parse_args(argv[1:]) options = parser.parse_args(argv[1:])
@ -1414,15 +1399,11 @@ def main(argv):
# Open files # Open files
if options.input_file: if options.input_file:
source = open(options.input_file, 'rb') source = open(options.input_file, 'rb')
elif PY2:
source = sys.stdin
else: else:
source = sys.stdin.buffer source = sys.stdin.buffer
if options.output_file: if options.output_file:
output = open(options.output_file, 'wb') output = open(options.output_file, 'wb')
elif PY2:
output = sys.stdout
else: else:
output = sys.stdout.buffer output = sys.stdout.buffer

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file legacy_lyxpreview2ppm.py # file legacy_lyxpreview2ppm.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -115,7 +113,7 @@ def legacy_extract_metrics_info(log_file):
success = 1 success = 1
match = data_re.search(line) match = data_re.search(line)
if match == None: if match == None:
error("Unexpected data in %s\n%s" % (log_file, line)) error(f"Unexpected data in {log_file}\n{line}")
if snippet: if snippet:
ascent = float(match.group(2)) ascent = float(match.group(2))
@ -145,11 +143,11 @@ def legacy_extract_metrics_info(log_file):
except: except:
# Unable to open the file, but do nothing here because # Unable to open the file, but do nothing here because
# the calling function will act on the value of 'success'. # the calling function will act on the value of 'success'.
warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file) warning(f'Warning in legacy_extract_metrics_info! Unable to open "{log_file}"')
warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1])) warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
if success == 0: if success == 0:
error("Failed to extract metrics info from %s" % log_file) error(f"Failed to extract metrics info from {log_file}")
return results return results
@ -176,7 +174,7 @@ def extract_resolution(log_file, dpi):
if match != None: if match != None:
match = extract_decimal_re.search(line) match = extract_decimal_re.search(line)
if match == None: if match == None:
error("Unable to parse: %s" % line) error(f"Unable to parse: {line}")
fontsize = float(match.group(1)) fontsize = float(match.group(1))
found_fontsize = 1 found_fontsize = 1
continue continue
@ -427,13 +425,12 @@ def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False)
dvi_file = latex_file_re.sub(".dvi", latex_file) dvi_file = latex_file_re.sub(".dvi", latex_file)
ps_file = latex_file_re.sub(".ps", latex_file) ps_file = latex_file_re.sub(".ps", latex_file)
dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file) dvips_call = f'{dvips} -i -o "{ps_file}" "{dvi_file}"'
dvips_failed = False dvips_failed = False
dvips_status, dvips_stdout = run_command(dvips_call) dvips_status, dvips_stdout = run_command(dvips_call)
if dvips_status: if dvips_status:
warning('Failed: %s %s ... looking for PDF' \ warning(f'Failed: {os.path.basename(dvips)} {dvi_file} ... looking for PDF')
% (os.path.basename(dvips), dvi_file))
dvips_failed = True dvips_failed = True
return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics) return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
@ -515,7 +512,7 @@ def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMe
conv_status, conv_stdout = run_command(conv_call) conv_status, conv_stdout = run_command(conv_call)
if conv_status: if conv_status:
error("Failed: %s %s" % (os.path.basename(conv), pdf_file)) error(f"Failed: {os.path.basename(conv)} {pdf_file}")
else: else:
# Model for calling the converter on each file # Model for calling the converter on each file
if use_pdftocairo and epstopdf != None: if use_pdftocairo and epstopdf != None:
@ -537,11 +534,10 @@ def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMe
# Call the converter for each file # Call the converter for each file
for file in ps_files: for file in ps_files:
i = i + 1 i = i + 1
progress("Processing page %s, file %s" % (i, file)) progress(f"Processing page {i}, file {file}")
if use_pdftocairo and epstopdf != None: if use_pdftocairo and epstopdf != None:
conv_name = "epstopdf" conv_name = "epstopdf"
conv_status, conv_stdout = run_command("%s --outfile=%s.pdf %s" conv_status, conv_stdout = run_command(f"{epstopdf} --outfile={file}.pdf {file}")
% (epstopdf, file, file))
if not conv_status: if not conv_status:
conv_name = "pdftocairo" conv_name = "pdftocairo"
file = file + ".pdf" file = file + ".pdf"
@ -552,7 +548,7 @@ def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMe
if conv_status: if conv_status:
# The converter failed, keep track of this # The converter failed, keep track of this
warning("%s failed on page %s, file %s" % (conv_name, i, file)) warning(f"{conv_name} failed on page {i}, file {file}")
failed_pages.append(i) failed_pages.append(i)
# Pass failed pages to pdflatex # Pass failed pages to pdflatex

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file lyxpak.py # file lyxpak.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -15,16 +13,10 @@
# a gzip compressed tar archive on *nix. This can be controlled by command # a gzip compressed tar archive on *nix. This can be controlled by command
# line options, however. # line options, however.
from __future__ import print_function
import gzip, os, re, sys import gzip, os, re, sys
from io import BytesIO from io import BytesIO
import subprocess import subprocess
# Provide support for both python 2 and 3
if sys.version_info[0] != 2:
def unicode(arg, enc):
return arg
# The path to the current python executable. sys.executable may fail, so in # The path to the current python executable. sys.executable may fail, so in
# this case we revert to simply calling "python" from the path. # this case we revert to simply calling "python" from the path.
PYTHON_BIN = sys.executable if sys.executable else "python" PYTHON_BIN = sys.executable if sys.executable else "python"
@ -118,13 +110,13 @@ def gather_files(curfile, incfiles, lyx2lyx):
try: try:
l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, tmp.name]) l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, tmp.name])
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
error('%s failed to convert "%s"' % (lyx2lyx, tostr(curfile))) error(f'{lyx2lyx} failed to convert "{tostr(curfile)}"')
os.unlink(tmp.name) os.unlink(tmp.name)
else: else:
try: try:
l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, curfile]) l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, curfile])
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
error('%s failed to convert "%s"' % (lyx2lyx, tostr(curfile))) error(f'{lyx2lyx} failed to convert "{tostr(curfile)}"')
if l2l_stdout.startswith(b"\x1f\x8b"): if l2l_stdout.startswith(b"\x1f\x8b"):
l2l_stdout = gzip.GzipFile("", "rb", 0, BytesIO(l2l_stdout)).read() l2l_stdout = gzip.GzipFile("", "rb", 0, BytesIO(l2l_stdout)).read()
elif running_on_windows: elif running_on_windows:
@ -168,9 +160,9 @@ def gather_files(curfile, incfiles, lyx2lyx):
if not os.path.isabs(file): if not os.path.isabs(file):
file = os.path.join(curdir, file) file = os.path.join(curdir, file)
file_exists = False file_exists = False
if not os.path.isdir(unicode(file, 'utf-8')): if not os.path.isdir(file):
for ext in extlist: for ext in extlist:
if os.path.exists(unicode(file + ext, 'utf-8')): if os.path.exists(file + ext):
file = file + ext file = file + ext
file_exists = True file_exists = True
break break
@ -193,7 +185,7 @@ def gather_files(curfile, incfiles, lyx2lyx):
file = file[9:] file = file[9:]
if not os.path.isabs(file): if not os.path.isabs(file):
file = os.path.join(curdir, file + b'.bst') file = os.path.join(curdir, file + b'.bst')
if os.path.exists(unicode(file, 'utf-8')): if os.path.exists(file):
incfiles.append(abspath(file)) incfiles.append(abspath(file))
i += 1 i += 1
continue continue
@ -208,7 +200,7 @@ def gather_files(curfile, incfiles, lyx2lyx):
file = bibfiles[j] + b'.bib' file = bibfiles[j] + b'.bib'
else: else:
file = os.path.join(curdir, bibfiles[j] + b'.bib') file = os.path.join(curdir, bibfiles[j] + b'.bib')
if os.path.exists(unicode(file, 'utf-8')): if os.path.exists(file):
incfiles.append(abspath(file)) incfiles.append(abspath(file))
j += 1 j += 1
i += 1 i += 1
@ -297,13 +289,11 @@ def main(args):
lyx2lyx = param lyx2lyx = param
elif opt == "-o": elif opt == "-o":
outdir = param outdir = param
if not os.path.isdir(unicode(outdir, 'utf-8')): if not os.path.isdir(outdir):
error('Error: "%s" is not a directory.' % outdir) error('Error: "%s" is not a directory.' % outdir)
lyxfile = argv[0] lyxfile = argv[0]
if not running_on_windows: if not os.path.exists(lyxfile):
lyxfile = unicode(lyxfile, sys.getfilesystemencoding()).encode('utf-8')
if not os.path.exists(unicode(lyxfile, 'utf-8')):
error('File "%s" not found.' % tostr(lyxfile)) error('File "%s" not found.' % tostr(lyxfile))
# Check that it actually is a LyX document # Check that it actually is a LyX document
@ -357,7 +347,7 @@ def main(args):
incfiles.sort() incfiles.sort()
if topdir != '': if topdir != '':
os.chdir(unicode(topdir, 'utf-8')) os.chdir(topdir)
# Create the archive # Create the archive
try: try:

View File

@ -1,5 +1,4 @@
#! /usr/bin/python3 #! /usr/bin/python3
# -*- coding: utf-8 -*-
# file lyxpaperview.py # file lyxpaperview.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file lyxpreview2bitmap.py # file lyxpreview2bitmap.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -75,7 +73,6 @@
# Moreover dvipng can't work with PDF files, so, if the CONVERTER # Moreover dvipng can't work with PDF files, so, if the CONVERTER
# paramter is pdflatex we have to fallback to legacy route (step 2). # paramter is pdflatex we have to fallback to legacy route (step 2).
from __future__ import print_function
import getopt, glob, os, re, shutil, sys, tempfile import getopt, glob, os, re, shutil, sys, tempfile
@ -89,8 +86,6 @@ from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
pdflatex_commands, progress, run_command, run_latex, run_tex, \ pdflatex_commands, progress, run_command, run_latex, run_tex, \
warning, write_metrics_info warning, write_metrics_info
PY2 = sys.version_info[0] == 2
def usage(prog_name): def usage(prog_name):
msg = """ msg = """
Usage: %s <options> <input file> Usage: %s <options> <input file>
@ -202,7 +197,7 @@ def convert_to_ppm_format(pngtopnm, basename):
for png_file in glob.glob("%s*.png" % basename): for png_file in glob.glob("%s*.png" % basename):
ppm_file = png_file_re.sub(".ppm", png_file) ppm_file = png_file_re.sub(".ppm", png_file)
p2p_cmd = '%s "%s"' % (pngtopnm, png_file) p2p_cmd = f'{pngtopnm} "{png_file}"'
p2p_status, p2p_stdout = run_command(p2p_cmd) p2p_status, p2p_stdout = run_command(p2p_cmd)
if p2p_status: if p2p_status:
error("Unable to convert %s to ppm format" % png_file) error("Unable to convert %s to ppm format" % png_file)
@ -226,7 +221,7 @@ def find_ps_pages(dvi_file):
# and inclusion of PDF/PNG/JPG files. # and inclusion of PDF/PNG/JPG files.
# This is required for correct rendering of PSTricks and TikZ # This is required for correct rendering of PSTricks and TikZ
dv2dt = find_exe_or_terminate(["dv2dt"]) dv2dt = find_exe_or_terminate(["dv2dt"])
dv2dt_call = '%s "%s"' % (dv2dt, dvi_file) dv2dt_call = f'{dv2dt} "{dvi_file}"'
# The output from dv2dt goes to stdout # The output from dv2dt goes to stdout
dv2dt_status, dv2dt_output = run_command(dv2dt_call) dv2dt_status, dv2dt_output = run_command(dv2dt_call)
@ -333,7 +328,7 @@ def main(argv):
"debug", "dpi=", "fg=", "help", "latex=", "lilypond", "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
"lilypond-book=", "png", "ppm", "verbose"]) "lilypond-book=", "png", "ppm", "verbose"])
except getopt.GetoptError as err: except getopt.GetoptError as err:
error("%s\n%s" % (err, usage(script_name))) error(f"{err}\n{usage(script_name)}")
opts.reverse() opts.reverse()
for opt, val in opts: for opt, val in opts:
@ -367,7 +362,7 @@ def main(argv):
# Determine input file # Determine input file
if len(args) != 1: if len(args) != 1:
err = "A single input file is required, %s given" % (len(args) or "none") err = "A single input file is required, %s given" % (len(args) or "none")
error("%s\n%s" % (err, usage(script_name))) error(f"{err}\n{usage(script_name)}")
input_path = args[0] input_path = args[0]
dir, latex_file = os.path.split(input_path) dir, latex_file = os.path.split(input_path)
@ -394,18 +389,11 @@ def main(argv):
progress("Resolution (dpi): %s" % dpi) progress("Resolution (dpi): %s" % dpi)
progress("File to process: %s" % input_path) progress("File to process: %s" % input_path)
# For python > 2 convert strings to bytes fg_color = bytes(fg_color, 'ascii')
if not PY2: bg_color = bytes(bg_color, 'ascii')
fg_color = bytes(fg_color, 'ascii')
bg_color = bytes(bg_color, 'ascii')
fg_color_dvipng = make_texcolor(fg_color, False) fg_color_dvipng = make_texcolor(fg_color, False).decode('ascii')
bg_color_dvipng = make_texcolor(bg_color, False) bg_color_dvipng = make_texcolor(bg_color, False).decode('ascii')
# For python > 2 convert bytes to string
if not PY2:
fg_color_dvipng = fg_color_dvipng.decode('ascii')
bg_color_dvipng = bg_color_dvipng.decode('ascii')
# External programs used by the script. # External programs used by the script.
latex = find_exe_or_terminate(latex or latex_commands) latex = find_exe_or_terminate(latex or latex_commands)

View File

@ -300,7 +300,7 @@ def run_latex(latex, latex_file, bibtex = None):
def run_tex(tex, tex_file): def run_tex(tex, tex_file):
tex_call = '%s "%s"' % (tex, tex_file) tex_call = f'{tex} "{tex_file}"'
tex_status, tex_stdout = run_command(tex_call) tex_status, tex_stdout = run_command(tex_call)
if tex_status: if tex_status:
@ -347,7 +347,7 @@ def check_latex_log(log_file):
found_error = False found_error = False
match = data_re.search(line) match = data_re.search(line)
if match == None: if match == None:
error("Unexpected data in %s\n%s" % (log_file, line)) error(f"Unexpected data in {log_file}\n{line}")
error_pages.append(int(match.group(1))) error_pages.append(int(match.group(1)))

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""Parser for command line options. """Parser for command line options.
This module helps scripts to parse the command line arguments in This module helps scripts to parse the command line arguments in
@ -83,7 +81,7 @@ def getopt(args, shortopts, longopts = []):
""" """
opts = [] opts = []
if type(longopts) == type(""): if type(longopts) == str:
longopts = [longopts] longopts = [longopts]
else: else:
longopts = list(longopts) longopts = list(longopts)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file prefs2prefs.py # file prefs2prefs.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -18,7 +16,6 @@
# #
# The format of the existing files was format 0, as of 2.0.alpha6. # The format of the existing files was format 0, as of 2.0.alpha6.
from __future__ import print_function
import os, re, string, sys import os, re, string, sys
from getopt import getopt from getopt import getopt
import io import io
@ -28,7 +25,7 @@ import io
def trim_bom(line): def trim_bom(line):
" Remove byte order mark." " Remove byte order mark."
if line[0:3] == u"\357\273\277": if line[0:3] == "\357\273\277":
return line[3:] return line[3:]
else: else:
return line return line
@ -128,8 +125,8 @@ def main(argv):
source = sys.stdin source = sys.stdin
output = sys.stdout output = sys.stdout
elif len(args) == 2: elif len(args) == 2:
source = io.open(args[0], 'r', encoding='utf_8', errors='surrogateescape') source = open(args[0], encoding='utf_8', errors='surrogateescape')
output = io.open(args[1], 'w', encoding='utf_8', newline='\n') output = open(args[1], 'w', encoding='utf_8', newline='\n')
opened_files = True opened_files = True
else: else:
usage() usage()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file prefs2prefs-lfuns.py # file prefs2prefs-lfuns.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file prefs2prefs-prefs.py # file prefs2prefs-prefs.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.
@ -271,7 +269,7 @@ def latex_flavor(line):
if flavor == "latex": if flavor == "latex":
return no_match return no_match
return (True, return (True,
"\\converter \"%s\" \"%s\" \"%s\" \"latex=%s\"" % (conv, fmat, args, flavor)) f"\\converter \"{conv}\" \"{fmat}\" \"{args}\" \"latex={flavor}\"")
emre = re.compile(r'^\\format\s+(.*)\s+"(document[^"]*?)"', re.IGNORECASE) emre = re.compile(r'^\\format\s+(.*)\s+"(document[^"]*?)"', re.IGNORECASE)
@ -284,7 +282,7 @@ def export_menu(line):
fmat = m.group(1) fmat = m.group(1)
opts = m.group(2) opts = m.group(2)
return (True, return (True,
"\\Format %s \"%s,menu=export\"" % (fmat, opts)) f"\\Format {fmat} \"{opts},menu=export\"")
# End format 1 conversions (for LyX 2.0) # End format 1 conversions (for LyX 2.0)
######################################## ########################################
@ -301,7 +299,7 @@ def zipped_native(line):
fmat = m.group(1) fmat = m.group(1)
opts = m.group(2) opts = m.group(2)
return (True, return (True,
"\\Format %s \"%s,zipped=native\"" % (fmat, opts)) f"\\Format {fmat} \"{opts},zipped=native\"")
def remove_default_papersize(line): def remove_default_papersize(line):
if not line.lower().startswith("\\default_papersize"): if not line.lower().startswith("\\default_papersize"):

View File

@ -1,5 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -*- coding: utf-8 -*-
# file svg2pdftex.py # file svg2pdftex.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
@ -28,7 +27,6 @@
# the real PDF file would be overwritten by a TeX file named outputfile.pdf. # the real PDF file would be overwritten by a TeX file named outputfile.pdf.
# #
from __future__ import print_function
import os, sys, re, subprocess import os, sys, re, subprocess

View File

@ -1,5 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -*- coding: utf-8 -*-
# file svg2pstex.py # file svg2pstex.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
@ -31,7 +30,6 @@
# This script converts an SVG image to something that latex can process # This script converts an SVG image to something that latex can process
# into high quality PostScript. # into high quality PostScript.
from __future__ import print_function
import os, sys, re, subprocess import os, sys, re, subprocess

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file tex_copy.py # file tex_copy.py
# This file is part of LyX, the document processor. # This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING. # Licence details can be found in the file COPYING.