Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes signal that only works in main thread of the main interpreter #133

Merged
merged 18 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions parfive/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import asyncio
import logging
import pathlib
import warnings
import threading
import contextlib
import urllib.parse
from typing import Union, Callable, Optional
Expand Down Expand Up @@ -223,6 +225,14 @@ def filepath(url, resp):
def _add_shutdown_signals(loop, task):
if os.name == "nt":
return

if threading.current_thread() != threading.main_thread():
warnings.warn(
"This download has been started in a thread which is not the main thread. You will not be able to interrupt the download.",
UserWarning,
)
return

for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, task.cancel)

Expand Down
32 changes: 32 additions & 0 deletions parfive/tests/test_downloader.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import platform
import threading
from pathlib import Path
from unittest import mock
from unittest.mock import patch
Expand Down Expand Up @@ -463,3 +464,34 @@ def test_proxy_passed_as_kwargs_to_get(tmpdir, url, proxy):
"proxy": proxy,
},
]


class CustomThread(threading.Thread):
def __init__(self, *args, **kwargs):
self.result = None
super().__init__(*args, **kwargs)

def run(self):
self.result = self._target(*self._args, **self._kwargs)


@skip_windows
def test_download_out_of_main_thread(httpserver, tmpdir):
tmpdir = str(tmpdir)
httpserver.serve_content(
"SIMPLE = T", headers={"Content-Disposition": "attachment; filename=testfile.fits"}
)
dl = Downloader()

dl.enqueue_file(httpserver.url, path=Path(tmpdir), max_splits=None)

thread = CustomThread(target=dl.download)
thread.start()

with pytest.warns(
UserWarning,
match="This download has been started in a thread which is not the main thread. You will not be able to interrupt the download.",
):
thread.join()

validate_test_file(thread.result)
Loading