Skip to content

Commit 7b9f918

Browse files
committed
Fall back to lz4 bindings if binary not available
1 parent ed6ed6d commit 7b9f918

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

src/xopen/__init__.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -568,28 +568,44 @@ def _open_lz4(
568568
if compresslevel is None:
569569
compresslevel = XOPEN_DEFAULT_LZ4_COMPRESSION
570570

571-
if lz4 is not None and (mode == "rb" or (mode in ("ab", "wb") and threads == 0)):
572-
# use Python bindings
573-
f = lz4.frame.LZ4FrameFile(filename, mode, compression_level=compresslevel)
574-
return f
575-
# use CLI program
571+
if lz4 is not None and (mode == "rb" or threads == 0):
572+
# Use Python bindings
573+
return lz4.frame.LZ4FrameFile(filename, mode, compression_level=compresslevel)
574+
575+
# Attempt to use the CLI program.
576+
#
577+
# Notes:
578+
#
579+
# - Multithreading in lz4 is only supported for compression, not for decompression.
580+
# - Older versions of lz4 (such as v1.94, which comes with Ubuntu 24.04) do not support
581+
# multithreading. They fail if one tries to pass the -T option.
582+
# - The newer versions use a default of -T0, which chooses the number of threads
583+
# automatically (presumably the number of available cores).
576584
try:
585+
# Try with the -T option first
586+
import copy
587+
588+
program_settings = copy.copy(_PROGRAM_SETTINGS["lz4"])
589+
program_settings.threads_flag = "-T"
577590
return _PipedCompressionProgram(
578-
filename,
579-
mode,
580-
compresslevel,
581-
threads,
582-
program_settings=_PROGRAM_SETTINGS["lz4"],
591+
filename, mode, compresslevel, threads, program_settings=program_settings
583592
)
593+
except FileNotFoundError:
594+
# Binary not found, use Python bindings if available
595+
if lz4 is not None:
596+
return lz4.frame.LZ4FrameFile(
597+
filename, mode, compression_level=compresslevel
598+
)
599+
else:
600+
raise
584601
except OSError:
585-
_program_settings = _PROGRAM_SETTINGS["lz4"]
586-
_program_settings.threads_flag = None
602+
# Assume the problem is that the -T option is not supported and re-try without it:
587603
return _PipedCompressionProgram(
588604
filename,
589605
mode,
590606
compresslevel,
591607
threads,
592-
program_settings=_program_settings,
608+
program_settings=_PROGRAM_SETTINGS["lz4"],
593609
)
594610

595611

0 commit comments

Comments
 (0)