Skip to content

Commit 35f0f49

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

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

src/xopen/__init__.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -568,28 +568,45 @@ 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+
program_settings = copy.copy(_PROGRAM_SETTINGS["lz4"])
588+
program_settings.threads_flag = "-T"
577589
return _PipedCompressionProgram(
578590
filename,
579591
mode,
580592
compresslevel,
581593
threads,
582-
program_settings=_PROGRAM_SETTINGS["lz4"],
594+
program_settings=program_settings
583595
)
596+
except FileNotFoundError:
597+
# Binary not found, use Python bindings if available
598+
if lz4 is not None:
599+
return lz4.frame.LZ4FrameFile(filename, mode, compression_level=compresslevel)
600+
else:
601+
raise
584602
except OSError:
585-
_program_settings = _PROGRAM_SETTINGS["lz4"]
586-
_program_settings.threads_flag = None
603+
# Assume the problem is that the -T option is not supported and re-try without it:
587604
return _PipedCompressionProgram(
588605
filename,
589606
mode,
590607
compresslevel,
591608
threads,
592-
program_settings=_program_settings,
609+
program_settings=_PROGRAM_SETTINGS["lz4"],
593610
)
594611

595612

0 commit comments

Comments
 (0)