]> git.lyx.org Git - lyx.git/commitdiff
Update Python scripts to Python 3+
authorJosé Matos <jamatos@lyx.org>
Mon, 10 Jun 2024 10:29:56 +0000 (11:29 +0100)
committerJosé Matos <jamatos@lyx.org>
Mon, 10 Jun 2024 10:29:56 +0000 (11:29 +0100)
Remove support for Python 2

Use formatted strings where appropriated

27 files changed:
lib/scripts/TeXFiles.py
lib/scripts/clean_dvi.py
lib/scripts/convertDefault.py
lib/scripts/convert_pdf.py
lib/scripts/csv2lyx.py
lib/scripts/docbook2epub.py
lib/scripts/docbook_copy.py
lib/scripts/ext_copy.py
lib/scripts/fen2ascii.py
lib/scripts/fig2pdftex.py
lib/scripts/fig2pstex.py
lib/scripts/fig_copy.py
lib/scripts/html2latexwrapper.py
lib/scripts/include_bib.py
lib/scripts/layout2layout.py
lib/scripts/legacy_lyxpreview2ppm.py
lib/scripts/lyxpak.py
lib/scripts/lyxpaperview.py
lib/scripts/lyxpreview2bitmap.py
lib/scripts/lyxpreview_tools.py
lib/scripts/lyxwin_getopt.py
lib/scripts/prefs2prefs.py
lib/scripts/prefs2prefs_lfuns.py
lib/scripts/prefs2prefs_prefs.py
lib/scripts/svg2pdftex.py
lib/scripts/svg2pstex.py
lib/scripts/tex_copy.py

index a5787eaacba4ce01fa28adb16f1bc48af073bcb6..c41d83f9a7f0e734751c26c1a9082fde38dbc355 100755 (executable)
@@ -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'
index 317ea922224de5fd4fa276ce498b5abe5b8015d9..4f7d73dc67457c6cafe7b22bd3f3cd520f93e62a 100644 (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)
index d04fa78799ba62f7a7f5a54a0eac8560970d15e2..460f712fe3f028ac9526ead93721ff32be2d3313 100644 (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)
index e1996259f17463cda7917c85c15a228d63b04e1d..881be6a25c87607213dad79d771b8dc24d0ced8a 100644 (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.
index 4547c7d1c4a3311336e39334e3cb70ff5e448295..eba6533e8f448b758617289fbaaf2e789ecd3fe9 100644 (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.
index 0e9d268a473288a361977aeadc47078349bc1d40..5cd8593dbbbfc0a5e963d3066e1f2c06a9e0cd67 100644 (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:
index 186bbe554f78e6bcb1949495c43a87d80a9ae4e0..9f483c04cf38a2d283328e65577c948ca54b1005 100644 (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()
index 2d4b386b242fdc6ae144a769169a73b2fc19be54..21380de12ff7d5abbf8ff91c54603f8b07cc2083 100644 (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
index 74087440e20ed8890bca120435c9fe23b8279086..8a98bcbc92d5bd680dc1678289f7ee48c9019517 100644 (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()
index 10e9c5a89d3a68c7db32bdf30402b2b757114868..c7188d8e43dd0e972f85a954e5d58c66f5f18558 100644 (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.
index 90e163de40b2819b3a1d134e1a48b062117afa67..5a3ee854fb3f58a8f1d1c62a2cf6a00184c5fa7a 100644 (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)
index a398c1dbf526b249b34098dddec5f40aa0e58fbd..656bfabc525c7236dd9470b411f1eea0f4ca345d 100644 (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:
index 0629573cc57f89e6745ecef95d039164d247332e..407ee3c4ff4510606d03480670b0fe7e8baf99ce 100644 (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:
index 0fb5afb92af46238743a737c5a9f1259fac27ee7..a7b6520a9d3ebd7b974e55d13a0f98c299758666 100644 (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:]
 
index 665e717bfb1cab0dd0cb340c1af0e2bb99cd5c6d..a610da47616e8246042e5ee638f1f075a40a0b64 100644 (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
 
index 78034416365cc6e63ecdfc01c120ca715cc78616..c5b110b82d8e31c3845ee9addbf46f3f5dd932c5 100644 (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
index 07091f208c7515a014d866135e84b9bcb5f84889..0d9151592ea84f049b5422d6f2ed4791cf547968 100755 (executable)
@@ -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.
 # 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:
index 667c2bf999d87f02259bafaaec6172b5fbb316a1..3e40a630d7873b4cdc18b46a6e27c9e69891f782 100755 (executable)
@@ -1,5 +1,4 @@
 #! /usr/bin/python3
-# -*- coding: utf-8 -*-
 
 # file lyxpaperview.py
 # This file is part of LyX, the document processor.
index 719738d0027c7f4259019258c786be90bcb8cd11..ab9afaa21cc432c67b878656b53f7471b598acce 100755 (executable)
@@ -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_dvipng = make_texcolor(fg_color, False)
-    bg_color_dvipng = make_texcolor(bg_color, False)
+    fg_color = bytes(fg_color, 'ascii')
+    bg_color = bytes(bg_color, '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')
+    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)
index c75563d4644a79bbabc2698d2287b904611595c6..56ff33e38b168fed032ff4dc260446420672ff8e 100644 (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)))
 
index a6f356a084a346d69f70484e00513b15802e143d..90571896ee0275097d0091f375907f815256bbfb 100755 (executable)
@@ -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)
index 00d619de211d800978076b99583262a97c177b00..1194abdf7a3a24b753408efa26b05895abe65698 100644 (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()
index a3416a0e52d67eb722c7e5c8928968e2a28e2160..5c5501ebbdb66459e4650a013e83c84893695152 100644 (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.
index 69b97fd30ef146709cf6c4d1118297aa4787415d..fe7e0a1ff43b7b5ecc5db7392e70dfddc050ac2e 100644 (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"):
index 74266e55cb94a984ad6d51b96e3d739dcfc98b4e..aad6d0b321273b1821aa565fd110bc30939d6235 100644 (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
 
index 09d8ac7183625bda2663a33e0af57d20d129ce9f..33aedc226a0d735ce4f34b501caf87633716a99d 100644 (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
 
index 529b13e7d0e46401bf992c399d6db441f31e28a0..dac153a90685d91f9829b84448f7fb6256d02c0d 100644 (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.