1
0
Fork 0
forked from josch/img2pdf

Rip out remaining python3 support

https://www.enricozini.org/blog/2020/python/python-2-is-dead/
This commit is contained in:
Johannes 'josch' Schauer 2020-04-23 07:13:39 +02:00
parent 9449f96345
commit ceba6a8223
Signed by untrusted user: josch
GPG key ID: F2CBA5C78FBD83E1
3 changed files with 45 additions and 116 deletions

View file

@ -1,8 +1,6 @@
import sys import sys
from setuptools import setup from setuptools import setup
PY3 = sys.version_info[0] >= 3
VERSION = "0.3.4" VERSION = "0.3.4"
INSTALL_REQUIRES = ( INSTALL_REQUIRES = (
@ -13,9 +11,6 @@ TESTS_REQUIRE = (
'pdfrw', 'pdfrw',
) )
if not PY3:
INSTALL_REQUIRES += ('enum34',)
setup( setup(
name='img2pdf', name='img2pdf',

View file

@ -42,8 +42,6 @@ try:
except ImportError: except ImportError:
pass pass
PY3 = sys.version_info[0] >= 3
__version__ = "0.3.4" __version__ = "0.3.4"
default_dpi = 96.0 default_dpi = 96.0
papersizes = { papersizes = {
@ -574,49 +572,26 @@ class MyPdfWriter:
self.addobj(page) self.addobj(page)
if PY3: class MyPdfString:
@classmethod
class MyPdfString: def encode(cls, string, hextype=False):
@classmethod if hextype:
def encode(cls, string, hextype=False): return (
if hextype: b"< " + b" ".join(("%06x" % c).encode("ascii") for c in string) + b" >"
return ( )
b"< " else:
+ b" ".join(("%06x" % c).encode("ascii") for c in string) try:
+ b" >" string = string.encode("ascii")
) except UnicodeEncodeError:
else: string = b"\xfe\xff" + string.encode("utf-16-be")
try: # We should probably encode more here because at least
string = string.encode("ascii") # ghostscript interpretes a carriage return byte (0x0D) as a
except UnicodeEncodeError: # new line byte (0x0A)
string = b"\xfe\xff" + string.encode("utf-16-be") # PDF supports: \n, \r, \t, \b and \f
# We should probably encode more here because at least string = string.replace(b"\\", b"\\\\")
# ghostscript interpretes a carriage return byte (0x0D) as a string = string.replace(b"(", b"\\(")
# new line byte (0x0A) string = string.replace(b")", b"\\)")
# PDF supports: \n, \r, \t, \b and \f return b"(" + string + b")"
string = string.replace(b"\\", b"\\\\")
string = string.replace(b"(", b"\\(")
string = string.replace(b")", b"\\)")
return b"(" + string + b")"
else:
class MyPdfString(object):
@classmethod
def encode(cls, string, hextype=False):
if hextype:
return (
b"< "
+ b" ".join(("%06x" % c).encode("ascii") for c in string)
+ b" >"
)
else:
# This mimics exactely to what pdfrw does.
string = string.replace(b"\\", b"\\\\")
string = string.replace(b"(", b"\\(")
string = string.replace(b")", b"\\)")
return b"(" + string + b")"
class pdfdoc(object): class pdfdoc(object):
@ -1817,9 +1792,9 @@ def convert(*images, **kwargs):
for kwname, default in _default_kwargs.items(): for kwname, default in _default_kwargs.items():
if kwname not in kwargs: if kwname not in kwargs:
kwargs[kwname] = default kwargs[kwname] = default
if 'with_pdfrw' in kwargs: if "with_pdfrw" in kwargs:
global with_pdfrw global with_pdfrw
with_pdfrw = kwargs['with_pdfrw'] with_pdfrw = kwargs["with_pdfrw"]
pdf = pdfdoc( pdf = pdfdoc(
"1.3", "1.3",
@ -2109,39 +2084,23 @@ def parse_borderarg(string):
def input_images(path): def input_images(path):
if path == "-": if path == "-":
# we slurp in all data from stdin because we need to seek in it later # we slurp in all data from stdin because we need to seek in it later
if PY3: result = sys.stdin.buffer.read()
result = sys.stdin.buffer.read()
else:
result = sys.stdin.read()
if len(result) == 0: if len(result) == 0:
raise argparse.ArgumentTypeError('"%s" is empty' % path) raise argparse.ArgumentTypeError('"%s" is empty' % path)
else: else:
if PY3: try:
try: if os.path.getsize(path) == 0:
if os.path.getsize(path) == 0: raise argparse.ArgumentTypeError('"%s" is empty' % path)
raise argparse.ArgumentTypeError('"%s" is empty' % path) # test-read a byte from it so that we can abort early in case
# test-read a byte from it so that we can abort early in case # we cannot read data from the file
# we cannot read data from the file with open(path, "rb") as im:
with open(path, "rb") as im: im.read(1)
im.read(1) except IsADirectoryError:
except IsADirectoryError: raise argparse.ArgumentTypeError('"%s" is a directory' % path)
raise argparse.ArgumentTypeError('"%s" is a directory' % path) except PermissionError:
except PermissionError: raise argparse.ArgumentTypeError('"%s" permission denied' % path)
raise argparse.ArgumentTypeError('"%s" permission denied' % path) except FileNotFoundError:
except FileNotFoundError: raise argparse.ArgumentTypeError('"%s" does not exist' % path)
raise argparse.ArgumentTypeError('"%s" does not exist' % path)
else:
try:
if os.path.getsize(path) == 0:
raise argparse.ArgumentTypeError('"%s" is empty' % path)
# test-read a byte from it so that we can abort early in case
# we cannot read data from the file
with open(path, "rb") as im:
im.read(1)
except IOError as err:
raise argparse.ArgumentTypeError(str(err))
except OSError as err:
raise argparse.ArgumentTypeError(str(err))
result = path result = path
return result return result
@ -3085,10 +3044,7 @@ Report bugs at https://gitlab.mister-muffin.de/josch/img2pdf/issues
help="Prints version information and exits.", help="Prints version information and exits.",
) )
parser.add_argument( parser.add_argument(
"--gui", "--gui", dest="gui", action="store_true", help="run experimental tkinter gui"
dest="gui",
action="store_true",
help="run experimental tkinter gui",
) )
outargs = parser.add_argument_group( outargs = parser.add_argument_group(
@ -3453,10 +3409,7 @@ and left/right, respectively. It is not possible to specify asymmetric borders.
if len(args.images) == 0: if len(args.images) == 0:
logging.info("reading image from standard input") logging.info("reading image from standard input")
try: try:
if PY3: args.images = [sys.stdin.buffer.read()]
args.images = [sys.stdin.buffer.read()]
else:
args.images = [sys.stdin.read()]
except KeyboardInterrupt: except KeyboardInterrupt:
exit(0) exit(0)

View file

@ -10,12 +10,7 @@ from io import StringIO, BytesIO, TextIOWrapper
HERE = os.path.dirname(__file__) HERE = os.path.dirname(__file__)
PY3 = sys.version_info[0] >= 3 PdfReaderIO = StringIO
if PY3:
PdfReaderIO = StringIO
else:
PdfReaderIO = BytesIO
# Recompressing the image stream makes the comparison robust against output # Recompressing the image stream makes the comparison robust against output
# preserving changes in the zlib compress output bitstream # preserving changes in the zlib compress output bitstream
@ -480,29 +475,15 @@ def tiff_header_for_ccitt(width, height, img_size, ccitt_group=4):
class CommandLineTests(unittest.TestCase): class CommandLineTests(unittest.TestCase):
def test_main_help(self): def test_main_help(self):
if PY3: from contextlib import redirect_stdout
from contextlib import redirect_stdout f = StringIO()
f = StringIO() with redirect_stdout(f):
with redirect_stdout(f):
try:
img2pdf.main(['img2pdf', '--help'])
except SystemExit:
pass
res = f.getvalue()
self.assertIn('img2pdf', res)
else:
# silence output
sys_stdout = sys.stdout
sys.stdout = BytesIO()
try: try:
img2pdf.main(['img2pdf', '--help']) img2pdf.main(['img2pdf', '--help'])
except SystemExit: except SystemExit:
# argparse does sys.exit(0) on --help pass
res = sys.stdout.getvalue() res = f.getvalue()
self.assertIn('img2pdf', res) self.assertIn('img2pdf', res)
finally:
sys.stdout = sys_stdout
def test_suite(): def test_suite():