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
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -35,7 +33,6 @@
# relies on python and kpsewhich (no shell command is used).
#
from __future__ import print_function
import os, sys, re
cls_stylefile = 'clsFiles.lst'

View File

@ -94,7 +94,7 @@ def main(argv):
if dv2dt_status != None or len(dv2dt_data) == 0:
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.
dtl_data = manipulated_dtl(dv2dt_data)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file convertDefault.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -16,7 +14,6 @@
# replacement in ~/.lyx/scripts
# converts an image $2 (format $1) to $4 (format $3)
from __future__ import print_function
import os, re, sys
# 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'
# 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('Execution of "%s" failed.' % command, file= sys.stderr)
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('Execution of "%s" failed.' % command, file=sys.stderr)
sys.exit(1)

View File

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

View File

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

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file docbook2epub.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -11,7 +9,6 @@
# Usage:
# 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 os
@ -19,7 +16,6 @@ import shutil
import sys
import tempfile
import zipfile
from io import open # Required for Python 2.
def _parse_nullable_argument(arg):
@ -39,7 +35,7 @@ class DocBookToEpub:
args = sys.argv
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)
self.own_path = sys.argv[0]
@ -127,7 +123,7 @@ class DocBookToEpub:
# The XHTML files are also <item> tags:
# <item id="id-d0e2" href="index.xhtml" media-type="application/xhtml+xml"/>
try:
with open(self.package_opf, 'r') as f:
with open(self.package_opf) as f:
for line in f.readlines():
if '<item' in line and 'media-type="image' in line:
images.append(line.split('href="')[1].split('"')[0])
@ -154,7 +150,7 @@ class DocBookToEpub:
def change_image_paths(self, file):
# 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
with open(file, 'r', encoding='utf8') as f:
with open(file, encoding='utf8') as f:
contents = list(f)
with open(file, 'w', encoding='utf8') as f:

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file docbook_copy.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -55,7 +53,7 @@ class DocBookCopier:
def in_file_needs_lilypond(self):
# 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()
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
# file invalid.
# 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:
if "language='lilypond'" in line:
line = re.sub(
@ -179,7 +177,7 @@ class DocBookCopier:
if __name__ == '__main__':
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)
DocBookCopier(sys.argv).copy()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file ext_copy.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -53,7 +51,7 @@ def main(argv):
error(usage(progname))
abs_from_file = args[0]
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)
# output directory
@ -64,7 +62,7 @@ def main(argv):
if targext != '.':
to_dir += "." + targext
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):
# some kind of failure

View File

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

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file fig2pdf.py
# This file is part of LyX, the document processor.
# 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.
#
from __future__ import print_function
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
# a PDF file ${base}.pdf and place the text in a LaTeX file
# ${base}.pdftex_t for typesetting by pdflatex itself.
runCommand('fig2dev -Lpdftex -p1 %s %s.pdf' % (input, outbase))
runCommand('fig2dev -Lpdftex_t -p%s %s %s' % (outbase, input, output))
runCommand(f'fig2dev -Lpdftex -p1 {input} {outbase}.pdf')
runCommand(f'fig2dev -Lpdftex_t -p{outbase} {input} {output}')
else:
# Older versions of xfig cannot do this, so we emulate the behaviour using
# pstex and pstex_t output.
runCommand('fig2dev -Lpstex %s %s.pstex' % (input, outbase))
runCommand('fig2dev -Lpstex_t -p %s %s %s' % (outbase, input, output))
runCommand(f'fig2dev -Lpstex {input} {outbase}.pstex')
runCommand(f'fig2dev -Lpstex_t -p {outbase} {input} {output}')
# manipulates the Bounding Box info to enable gs to produce
# the appropriate PDF file from an EPS one.

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file fig2pstex.py
# This file is part of LyX, the document processor.
# 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.
#
from __future__ import print_function
import os, sys
# 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 PSTEX_T file
if os.system('fig2dev -Lpstex %s %s.eps' % (input, outbase)) != 0 or \
os.system('fig2dev -Lpstex_t -p%s %s %s' % (outbase, input, output)) != 0:
if os.system(f'fig2dev -Lpstex {input} {outbase}.eps') != 0 or \
os.system(f'fig2dev -Lpstex_t -p{outbase} {input} {output}') != 0:
print ('fig2dev fails')
sys.exit(1)

View File

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

View File

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

View File

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

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file layout2layout.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -365,19 +363,6 @@ currentFormat = 105
import os, re, sys
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):
sys.stderr.write(message + '\n')
@ -570,15 +555,15 @@ def convert(lines, end_format):
match = re_Format.match(lines[i])
if match:
formatline = i
format = int(match.group(4))
if 1 < format < end_format:
lines[i] = b"Format %d" % (format + 1)
format_ = int(match.group(4))
if 1 < format_ < end_format:
lines[i] = b"Format %d" % (format_ + 1)
only_comment = 0
elif format == end_format:
elif format_ == end_format:
# nothing to do
return format
return format_
else:
error('Cannot convert file format %s to %s' % (format, end_format))
error(f'Cannot convert file format {format_} to {end_format}')
else:
lines.insert(i, b"Format 2")
only_comment = 0
@ -1404,9 +1389,9 @@ def main(argv):
parser.add_argument("-t", "--to", type=int, dest="format", default= 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)")
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)")
options = parser.parse_args(argv[1:])
@ -1414,15 +1399,11 @@ def main(argv):
# Open files
if options.input_file:
source = open(options.input_file, 'rb')
elif PY2:
source = sys.stdin
else:
source = sys.stdin.buffer
if options.output_file:
output = open(options.output_file, 'wb')
elif PY2:
output = sys.stdout
else:
output = sys.stdout.buffer

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file legacy_lyxpreview2ppm.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
@ -115,7 +113,7 @@ def legacy_extract_metrics_info(log_file):
success = 1
match = data_re.search(line)
if match == None:
error("Unexpected data in %s\n%s" % (log_file, line))
error(f"Unexpected data in {log_file}\n{line}")
if snippet:
ascent = float(match.group(2))
@ -145,11 +143,11 @@ def legacy_extract_metrics_info(log_file):
except:
# Unable to open the file, but do nothing here because
# 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]))
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
@ -176,7 +174,7 @@ def extract_resolution(log_file, dpi):
if match != None:
match = extract_decimal_re.search(line)
if match == None:
error("Unable to parse: %s" % line)
error(f"Unable to parse: {line}")
fontsize = float(match.group(1))
found_fontsize = 1
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)
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_status, dvips_stdout = run_command(dvips_call)
if dvips_status:
warning('Failed: %s %s ... looking for PDF' \
% (os.path.basename(dvips), dvi_file))
warning(f'Failed: {os.path.basename(dvips)} {dvi_file} ... looking for PDF')
dvips_failed = True
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)
if conv_status:
error("Failed: %s %s" % (os.path.basename(conv), pdf_file))
error(f"Failed: {os.path.basename(conv)} {pdf_file}")
else:
# Model for calling the converter on each file
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
for file in ps_files:
i = i + 1
progress("Processing page %s, file %s" % (i, file))
progress(f"Processing page {i}, file {file}")
if use_pdftocairo and epstopdf != None:
conv_name = "epstopdf"
conv_status, conv_stdout = run_command("%s --outfile=%s.pdf %s"
% (epstopdf, file, file))
conv_status, conv_stdout = run_command(f"{epstopdf} --outfile={file}.pdf {file}")
if not conv_status:
conv_name = "pdftocairo"
file = file + ".pdf"
@ -552,7 +548,7 @@ def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMe
if conv_status:
# 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)
# Pass failed pages to pdflatex

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file lyxpak.py
# This file is part of LyX, the document processor.
# 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
# line options, however.
from __future__ import print_function
import gzip, os, re, sys
from io import BytesIO
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
# this case we revert to simply calling "python" from the path.
PYTHON_BIN = sys.executable if sys.executable else "python"
@ -118,13 +110,13 @@ def gather_files(curfile, incfiles, lyx2lyx):
try:
l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, tmp.name])
except subprocess.CalledProcessError:
error('%s failed to convert "%s"' % (lyx2lyx, tostr(curfile)))
error(f'{lyx2lyx} failed to convert "{tostr(curfile)}"')
os.unlink(tmp.name)
else:
try:
l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, curfile])
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"):
l2l_stdout = gzip.GzipFile("", "rb", 0, BytesIO(l2l_stdout)).read()
elif running_on_windows:
@ -168,9 +160,9 @@ def gather_files(curfile, incfiles, lyx2lyx):
if not os.path.isabs(file):
file = os.path.join(curdir, file)
file_exists = False
if not os.path.isdir(unicode(file, 'utf-8')):
if not os.path.isdir(file):
for ext in extlist:
if os.path.exists(unicode(file + ext, 'utf-8')):
if os.path.exists(file + ext):
file = file + ext
file_exists = True
break
@ -193,7 +185,7 @@ def gather_files(curfile, incfiles, lyx2lyx):
file = file[9:]
if not os.path.isabs(file):
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))
i += 1
continue
@ -208,7 +200,7 @@ def gather_files(curfile, incfiles, lyx2lyx):
file = bibfiles[j] + b'.bib'
else:
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))
j += 1
i += 1
@ -297,13 +289,11 @@ def main(args):
lyx2lyx = param
elif opt == "-o":
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)
lyxfile = argv[0]
if not running_on_windows:
lyxfile = unicode(lyxfile, sys.getfilesystemencoding()).encode('utf-8')
if not os.path.exists(unicode(lyxfile, 'utf-8')):
if not os.path.exists(lyxfile):
error('File "%s" not found.' % tostr(lyxfile))
# Check that it actually is a LyX document
@ -357,7 +347,7 @@ def main(args):
incfiles.sort()
if topdir != '':
os.chdir(unicode(topdir, 'utf-8'))
os.chdir(topdir)
# Create the archive
try:

View File

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

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file lyxpreview2bitmap.py
# This file is part of LyX, the document processor.
# 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
# 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
@ -89,8 +86,6 @@ from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
pdflatex_commands, progress, run_command, run_latex, run_tex, \
warning, write_metrics_info
PY2 = sys.version_info[0] == 2
def usage(prog_name):
msg = """
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):
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)
if p2p_status:
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.
# This is required for correct rendering of PSTricks and TikZ
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
dv2dt_status, dv2dt_output = run_command(dv2dt_call)
@ -333,7 +328,7 @@ def main(argv):
"debug", "dpi=", "fg=", "help", "latex=", "lilypond",
"lilypond-book=", "png", "ppm", "verbose"])
except getopt.GetoptError as err:
error("%s\n%s" % (err, usage(script_name)))
error(f"{err}\n{usage(script_name)}")
opts.reverse()
for opt, val in opts:
@ -367,7 +362,7 @@ def main(argv):
# Determine input file
if len(args) != 1:
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]
dir, latex_file = os.path.split(input_path)
@ -394,18 +389,11 @@ def main(argv):
progress("Resolution (dpi): %s" % dpi)
progress("File to process: %s" % input_path)
# For python > 2 convert strings to bytes
if not PY2:
fg_color = bytes(fg_color, 'ascii')
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)
bg_color_dvipng = make_texcolor(bg_color, False)
# 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')
fg_color_dvipng = make_texcolor(fg_color, False).decode('ascii')
bg_color_dvipng = make_texcolor(bg_color, False).decode('ascii')
# External programs used by the script.
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):
tex_call = '%s "%s"' % (tex, tex_file)
tex_call = f'{tex} "{tex_file}"'
tex_status, tex_stdout = run_command(tex_call)
if tex_status:
@ -347,7 +347,7 @@ def check_latex_log(log_file):
found_error = False
match = data_re.search(line)
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)))

View File

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

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# file prefs2prefs.py
# This file is part of LyX, the document processor.
# 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.
from __future__ import print_function
import os, re, string, sys
from getopt import getopt
import io
@ -28,7 +25,7 @@ import io
def trim_bom(line):
" Remove byte order mark."
if line[0:3] == u"\357\273\277":
if line[0:3] == "\357\273\277":
return line[3:]
else:
return line
@ -128,8 +125,8 @@ def main(argv):
source = sys.stdin
output = sys.stdout
elif len(args) == 2:
source = io.open(args[0], 'r', encoding='utf_8', errors='surrogateescape')
output = io.open(args[1], 'w', encoding='utf_8', newline='\n')
source = open(args[0], encoding='utf_8', errors='surrogateescape')
output = open(args[1], 'w', encoding='utf_8', newline='\n')
opened_files = True
else:
usage()

View File

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

View File

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

View File

@ -1,5 +1,4 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# file svg2pdftex.py
# 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.
#
from __future__ import print_function
import os, sys, re, subprocess

View File

@ -1,5 +1,4 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# file svg2pstex.py
# 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
# into high quality PostScript.
from __future__ import print_function
import os, sys, re, subprocess

View File

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