如何从工作线程导入Python异步模块?

发布于 2024-09-18 05:13:25 字数 1155 浏览 7 评论 0原文

我正在使用 GitPython 包 从 Python 访问 Git 存储库。这会拉入异步包。在 async/__init__.py 中,会发生以下情况:

def _init_signals():
    """Assure we shutdown our threads correctly when being interrupted"""
    import signal
    # ...
    signal.signal(signal.SIGINT, thread_interrupt_handler)

_init_signals()

如果一切都在主线程中,则效果很好。然而,当 git 的第一次导入(因此 async)发生在另一个线程上时,事情就会变得繁荣:

ValueError: signal only works in main thread

由于所有这些都在 Django 框架内运行,所以我无法控制线程。

我发现的一种解决方法是将 import async 放入 settings.py 中,它(显然)是在主线程上导入的。然而,这需要在每次安装的基础上完成,所以这对于我的 Django 应用程序的用户来说不是很好。

我尝试捕获异常,但引发异常的导入未完全完成,因此下一个 import async 也会失败。

你能想出任何半途而废的方法来解决这个问题吗?


更新:我注意到 Apache 的 mod_wsgi 足够聪明,可以忽略 signal 调用:

[Tue Sep 07 19:53:11 2010] [warn] mod_wsgi (pid=28595): Callback registration for signal 2 ignored.

不过,问题仍然存在于 Django 开发服务器上。

I'm using the GitPython package to access a Git repository from Python. This pulls in the async package. In async/__init__.py, the following happens:

def _init_signals():
    """Assure we shutdown our threads correctly when being interrupted"""
    import signal
    # ...
    signal.signal(signal.SIGINT, thread_interrupt_handler)

_init_signals()

This works fine if everything is in the main thread. However, when the first import of git (and thus async) happens on another thread, things go boom:

ValueError: signal only works in main thread

Since all this runs inside the Django framework, I have no control over threading.

One workaround I've found is to put import async into settings.py, which is (apparently) imported on the main thread. However, this needs to be done on a per-install basis, so it's not very nice towards users of my Django app.

I tried catching the exception, but an import that raised an exception does not fully complete, so the next import async will fail as well.

Can you think of any halfway decent method to work/hack around this problem?


Update: I noticed that Apache's mod_wsgi is smart enough to ignore the signal call:

[Tue Sep 07 19:53:11 2010] [warn] mod_wsgi (pid=28595): Callback registration for signal 2 ignored.

The problem remains with the Django development server, though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

毁梦 2024-09-25 05:13:28

如果您从 git 提取最新的异步代码,我怀疑这将为您解决,并在 补丁

If you pull the latest async code from git, I suspect this will be fixed for you and is called out as a non-fatal error in the patch

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文