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 3 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
9 changes: 9 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,13 @@ def filepath(url, resp):
def _add_shutdown_signals(loop, task):
if os.name == "nt":
return

if threading.current_thread() != threading.main_thread():
warnings.warn(
"Signal only works in main thread of the main interpreter and the handlers to interrupt the kernel have not been added."
AthKouloumvakos marked this conversation as resolved.
Show resolved Hide resolved
)
return

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

Expand Down
26 changes: 26 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,28 @@ 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)


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()
thread.join()

validate_test_file(thread.result)