python - 从 Twisted 调用 Python 代码

标签 python multithreading twisted

首先,我应该说这可能更多是一个设计问题,而不是代码本身。

我有一个包含一个服务器和多个客户端的网络(用 Twisted 编写,因为我需要这些异步非阻塞功能),这样的服务器-客户端耦合它只是接收-发送消息。

但是,在某些时候,我希望一个客户端在收到特定消息时运行 python 文件。该客户端应该继续监听服务器并与服务器对话,而且,如果需要,我应该能够停止该文件,所以我的第一个想法是为该 python 文件启动一个线程,然后忘记它。

最后应该是这样的:服务器向 ClientA 发送消息,ClientA 及其 dataReceived 函数解释该消息并决定运行该 python 文件(我不知道需要多长时间,并且可能包含阻塞调用) ,当该 python 文件完成运行时应将结果发送到 ClientB。

所以,问题是:

  • 对于 ClientA 中的 python 文件启动一个线程是个好主意吗?
  • 由于我想将该 python 文件的结果发送到 ClientB,我可以在该 python 文件中添加另一个 Reactor 循环吗?

无论如何,我非常感谢任何建议,因为 python 和twisted 都不是我的专长,所有这些想法可能都不是最好的。

谢谢!

最佳答案

初读时,我以为你是在暗示twisted不是python。如果您有这样的想法,请记住以下几点:

Twisted is a python framework, I.E. it is python. Specifically it's about getting the most out of a single process/thread/core by allowing the programmer to hand-tune the scheduling/order-of-ops in their own code (which is nearly the opposite of the typical use of threads).

While you can interact with threads in twisted, its quite tricky to do without ruining the efficiency of twisted. (for longer description of threads vs events see SO: https://stackoverflow.com/a/23876498/3334178 )

如果你真的想从扭曲的Python中生成新的Python(即让这项工作在不同的核心上运行),那么我会考虑将其作为一个进程生成,请参阅Glyph在这个SO中的答案:https://stackoverflow.com/a/5720492/3334178让优秀的图书馆能够完成这项工作。

进程提供了适当的分离,允许您扭曲的应用程序运行而不会明显减慢,您应该会发现您所有的启动/停止/暂停/终止需求都将得到满足。

具体回答您的问题:

Would it be starting a thread a good idea for that python file in ClientA?

我会说“不”,这通常不是一个好主意,在您的具体情况下,您应该考虑使用流程。

Can I have another reactor loop inside that python file?

严格来说,“不,你不能有多个 react 器” - 但twisted可以做的是同时管理数百或数千个单独的任务,所有任务都在同一个 react 器中,将满足你的需要。 IE。在一个 react ​​器中运行所有不同的异步任务,这就是twisted 的用途。

顺便说一句,我总是推荐以下twisted教程:krondo Twisted简介http://krondo.com/?page_id=1327虽然很长,但是如果你读完了,这样的工作就会变得非常清晰。

祝一切顺利!

关于python - 从 Twisted 调用 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872856/

相关文章:

python - crontab python子进程和服务重启

python - 无法使用 Pandas to_sql() 方法将数据插入到 Snowflake 数据库表中

python - 反序列化多对多 PUT 操作的 id 列表

python - 将 threading.Timer 与 asyncio 一起使用

python twisted - 发送的消息超时但没有得到响应

python - Twisted - 用一个 react 堆监听多个进程的多个端口

python - 我如何告诉 pylint 变量将在运行时定义?

python - 如何从 C++ 启动 Python 线程?

一组的 C++ mmap

带有 Twisted 的 Python Web 服务