Skip to content

Commit

Permalink
Fix warnings when closing half-initialized files
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelm committed Jan 15, 2024
1 parent 8d24106 commit e7caf0c
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/xopen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,6 @@ def __init__(
)
)

# TODO use a context manager
self.outfile = open(path, mode[0] + "b")
self.name: str = str(os.fspath(path))
self._mode: str = mode
self._program_args: List[str] = program_args
Expand All @@ -211,6 +209,7 @@ def __init__(
if threads is None:
threads = min(_available_cpu_count(), 4)
self._threads = threads
self.outfile = open(path, mode[0] + "b")
try:
self.process = self._open_process(
mode, compresslevel, threads, self.outfile
Expand Down Expand Up @@ -270,6 +269,9 @@ def close(self) -> None:
if self.closed:
return
super().close()
if not hasattr(self, "process"):
# Exception was raised during __init__
return
self._file.close()
retcode = self.process.wait()
self.outfile.close()
Expand Down Expand Up @@ -321,7 +323,7 @@ def __init__(
newline=None,
):
"""
Raise an OSError when pigz could not be found.
Raise an OSError when the binary could not be found.
"""
if mode not in ("r", "rt", "rb"):
raise ValueError(
Expand All @@ -344,13 +346,13 @@ def __init__(
threads = 1
program_args += [f"{threads_flag}{threads}"]
self._threads = threads
self.process = Popen(program_args, stdout=PIPE, stderr=PIPE)
self.name = path
self._mode = mode
self.process = Popen(program_args, stdout=PIPE, stderr=PIPE)

assert self.process.stdout is not None
_set_pipe_size_to_max(self.process.stdout.fileno())

self._mode = mode
if "b" not in mode:
self._file: IO = io.TextIOWrapper(
self.process.stdout, encoding=encoding, errors=errors, newline=newline
Expand All @@ -373,6 +375,9 @@ def close(self) -> None:
if self.closed:
return
super().close()
if not hasattr(self, "process"):
# Exception was raised during __init__
return
retcode = self.process.poll()
check_allowed_code_and_message = False
if retcode is None:
Expand Down Expand Up @@ -444,6 +449,8 @@ def _raise_if_error(

assert self.process.stderr is not None
if not stderr_message:
if self.process.stderr.closed:
return
stderr_message = self.process.stderr.read()

self._file.close()
Expand Down

0 comments on commit e7caf0c

Please sign in to comment.